diff --git a/quest/m2/ts-model/README.md b/quest/m2/ts-model/README.md index 435515c5f..cbc163c64 100644 --- a/quest/m2/ts-model/README.md +++ b/quest/m2/ts-model/README.md @@ -28,8 +28,8 @@ Decided with the maintainer on 2026-10-27, from a census of the model's 22 publi - This is an epic; each group of refusals is a child below. moq must work, but nothing in the translator is specific to moq: dependencies follow general rules, and moq's own - changes (safe `cfg` twins of its `unsafe`, `dyn Expiry` as an enum, dropping or binding - `hashlink`, `slab`, and `smallvec`) are one research-tier quest in moq's tree. + changes (safe `cfg` twins of its `unsafe`, dropping or binding `hashlink`, `slab`, and + `smallvec`) are one research-tier quest in moq's tree. - Until `unsafe` and trait objects translate, internal `unsafe` in moq-net and kio gets safe `cfg` twins in moq, so differential tests cover it, and a dependency containing `unsafe` is bound by the consumer. These are stopgaps: decided with the maintainer on diff --git a/quest/m3/ts-dyn.md b/quest/m3/ts-dyn.md index d7198442e..521a1e315 100644 --- a/quest/m3/ts-dyn.md +++ b/quest/m3/ts-dyn.md @@ -3,23 +3,21 @@ ## Goal [rust2-ts](/ts/README.md) translates the trait objects moq uses that it still refuses -(`Arc`, `Box` and `&dyn Fn`, and other crates' traits), with Rust's +(`Box` and `&dyn Fn`, `Arc`, and other crates' traits), with Rust's dispatch and drop order, proven by differential tests against native Rust, so a consumer neither rewrites nor binds them. ## Plan Decided with the maintainer on 2026-10-27: a stock crate translates with no annotations or -config, so trait objects move from never to not yet. Until this lands, moq rewrites -`dyn Expiry` as an enum and binds its boxed closures ([bindings](/ts/README.md#bindings)). +config, so trait objects move from never to not yet. Until this lands, moq binds its boxed +closures ([bindings](/ts/README.md#bindings)). - `&dyn Debug` and `&dyn Display` translate as functions writing their value, `dyn Future` - as an `rt.Future`, and `&dyn Trait`, `&mut dyn Trait`, and `Box` of the - crate's own traits as an object with the trait's methods, which a class per type wraps - the value in. Build the rest on those. -- `Arc`: an `Arc` unsized from an `Arc` shares its count, so the wrapper - can't replace the `Arc`'s value; its clone, drop, and deref must still see one count. - `Arc` has the same problem. + as an `rt.Future`, and `&dyn Trait`, `&mut dyn Trait`, `Box`, and + `Arc` of the crate's own traits as an object with the trait's methods, which + a class per type wraps the value in; an `Arc`'s is an `rt.ArcDyn` sharing the count of + the `Arc` it was made from. Build the rest on those. - Another crate's traits: `Fn*` objects can be the closure itself, as `&dyn Debug` is the function writing it; `Iterator`, `Error`, `Any`, and `bytes::Buf` need their std methods mapped onto the object. diff --git a/ts/README.md b/ts/README.md index b4891fc01..cfb64fd02 100644 --- a/ts/README.md +++ b/ts/README.md @@ -87,7 +87,7 @@ in `rt/str.ts`, collections in `rt/collections.ts`, ownership, atomics, and asyn | `Ordering`, `DefaultHasher` | `rt.Ordering`, which is `-1`, `0`, or `1`; `rt.Hasher` | | `Duration` | `rt.Duration`: `{ secs, nanos }`, std's whole seconds as an `rt.u64` and the nanoseconds past them, never changed once made | | closure | an arrow function, with `[Symbol.dispose]` if it owns a value that drops | -| `&dyn Trait`, `&mut dyn Trait`, `Box` | an object with the trait's methods, its supertraits' included: `shape.area$Shape()` | +| `&dyn Trait`, `&mut dyn Trait`, `Box`, `Arc` | an object with the trait's methods, its supertraits' included: `shape.area$Shape()`; behind an `Arc`, an `rt.ArcDyn` sharing the count of the `Arc` it was made from | | constant | its value, inlined as Rust inlines it | | a type that drops | a class with `[Symbol.dispose]`: its `Drop` impl, then its fields | | a type's function | a function of the type's module, taking `self` first: `Decoder.slice(dec, 4)` after `import * as Decoder` | @@ -234,7 +234,7 @@ panics leaves the rest to drop as Rust's does: a class's glue and the runtime's go on to the rest of the value and its container, but a hash table leaks its other entries, as std's does. -A trait object of the crate's own trait, behind `&`, `&mut`, or `Box`, is an object with +A trait object of the crate's own trait, behind `&`, `&mut`, `Box`, or `Arc`, is an object with a method for each function a call can dispatch to, its supertraits' included, named for its trait as an impl's function is and taking what follows `self`: `shape.area$Shape()`. The trait's module exports its type, `Shape.Shape` from `dyns.Shape.ts`, which a TS @@ -242,10 +242,13 @@ caller can implement. A coercion wraps the value in a class of its type's, `new Shape.Square(sq)`, whose methods call that type's impl; one from a `&mut` to a value JS copies holds its `rt.Place`, so `&mut self` writes where the value is. An upcast is the same object. A `Box` drops what it holds through its `[Symbol.dispose]`, which -a TS caller's object may leave out. A trait object of another crate's trait, but for -`&dyn Debug`, `&dyn Display`, and `dyn Future`, of a generic trait or one with an -associated type, of a byte array, or behind any other pointer, such as an `Arc` or a -struct's last field, is refused. +a TS caller's object may leave out. An `Arc` unsized to an `Arc`, or to an +`Arc`, is an `rt.ArcDyn`: the object a box of its value would be, and the +`Arc` it was made from, whose one count both sides' clones and drops change, and the +last of which drops the value. `Arc::ptr_eq` compares the `Arc`s. A trait object of +another crate's trait, but for `&dyn Debug`, `&dyn Display`, and `dyn Future`, of a +generic trait or one with an associated type, of a byte array, or behind any other +pointer, such as a `Weak` or a struct's last field, is refused. An `async fn` returns a future without running anything: an instance of a class of its own (`sumFuture`), the state machine MIR's coroutine transform makes. Its fields are the @@ -462,7 +465,7 @@ they need. `unsafe` and raw pointers ([unsafe](/quest/m3/ts-unsafe.md)), and trait objects other than `&dyn Debug`, `&dyn Display`, `dyn Future`, and the crate's own traits' behind `&`, `&mut`, -or `Box` ([trait objects](/quest/m3/ts-dyn.md)), fail translation. Until they translate, an item that needs one, such as a boxed closure, binds to +`Box`, or `Arc` ([trait objects](/quest/m3/ts-dyn.md)), fail translation. Until they translate, an item that needs one, such as a boxed closure, binds to hand-written TS ([bindings](#bindings)). These fail translation: formatting and parsing an `f64`, and `f64::clamp`, whose panic formats them ([float formatting](/quest/m2/ts-model/floats.md)), `f32` ([`f32`](/quest/m3/ts-f32.md)), statics, async closures, a closure that owns a value diff --git a/ts/fixtures/lang/caller.ts b/ts/fixtures/lang/caller.ts index 530d2ef26..8c5af1882 100644 --- a/ts/fixtures/lang/caller.ts +++ b/ts/fixtures/lang/caller.ts @@ -242,4 +242,12 @@ const cellScripts = [ ]; const cells = Array.from({ length: 256 }, (_, kind) => cellScripts.map((script) => Uint8Array.of(cellsOp, kind, ...script))).flat(); -export const cases: Uint8Array[] = [...loops, ...durations, ...ints(), ...utf8, ...floats, ...dyns, ...cells]; +/** + * `dyns::shared` too short to run, and with `Arc`s of each type, the last count of each at + * zero and at the top of its range. + */ +const shared = [[], [1], [0, 0], [255, 255, 0, 1, 2, 3, 4, 5], [7, 0xff, 255, 254, 253]].map((bytes) => + Uint8Array.of(op("dyns::shared"), 0, ...bytes), +); + +export const cases: Uint8Array[] = [...loops, ...durations, ...ints(), ...utf8, ...floats, ...dyns, ...cells, ...shared]; diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts index f5c010fdb..0ac6a16e7 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -5,6 +5,7 @@ import { copy$u8s_u8s } from "../lib.ts"; import type * as Nibble from "../collections.Nibble.ts"; import type * as Rank from "../collections.Rank.ts"; import type * as Tally from "../collections.Tally.ts"; +import type * as Shape from "../dyns.Shape.ts"; import { side, order } from "../keys.ts"; import type * as Hop from "../keys.Hop.ts"; import type * as Side from "../keys.Side.ts"; @@ -13,7 +14,7 @@ import { from$From_Dir_u8 } from "../shapes.ts"; import type * as Dir from "../shapes.Dir.ts"; import type * as Meters from "../shapes.Meters.ts"; import type * as Point from "../shapes.Point.ts"; -import type * as Shape from "../shapes.Shape.ts"; +import type * as shapes_Shape from "../shapes.Shape.ts"; import type * as Short from "../splits.Short.ts"; export function isSomeAnd$Option_u8_bools_closure0(self: rt.u8 | undefined, f: (a0: rt.u8) => boolean): boolean { @@ -135,7 +136,14 @@ export function unwrapOrDefault$Option_u8(self: rt.u8 | undefined): rt.u8 { return self; } -export function map$Option_Dir_Shape_rematched_closure1(self: Dir.Dir | undefined, f: (a0: Dir.Dir) => Shape.Shape): Shape.Shape | undefined { +export function map$Option_Arc_dyn_Shape_u32_shared_closure0(self: rt.Arc | undefined, f: (a0: rt.Arc) => rt.u32): rt.u32 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function map$Option_Dir_Shape_rematched_closure1(self: Dir.Dir | undefined, f: (a0: Dir.Dir) => shapes_Shape.Shape): shapes_Shape.Shape | undefined { if (self === undefined) { return undefined; } @@ -317,7 +325,7 @@ export function mapOr$Option_Rank_Tally_u8_hash_maps_closure11(self: [Rank.Rank, return f(self); } -export function mapOr$Option_Shape_u8_rematched_closure0(self: Shape.Shape | undefined, default_: rt.u8, f: (a0: Shape.Shape) => rt.u8): rt.u8 { +export function mapOr$Option_Shape_u8_rematched_closure0(self: shapes_Shape.Shape | undefined, default_: rt.u8, f: (a0: shapes_Shape.Shape) => rt.u8): rt.u8 { if (self === undefined) { return default_; } diff --git a/ts/fixtures/lang/expected/dyns.Hits.ts b/ts/fixtures/lang/expected/dyns.Hits.ts new file mode 100644 index 000000000..7a4a605b2 --- /dev/null +++ b/ts/fixtures/lang/expected/dyns.Hits.ts @@ -0,0 +1,38 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** Provided, and overridden by one impl. */ +export function sides$Shape(_self: Hits): rt.u8 { + return 4; +} + +export function intoArea$Shape(self: Hits): rt.u32 { + return rt.u32WrappingAdd(area$Shape(self), 1); +} + +/** Over early-bound lifetimes, which its signature takes as arguments too. */ +export function larger$Shape(self: Hits, other: rt.u32): rt.u32 { + return rt.max(area$Shape(self), other); +} + +/** Writes through a `&mut` to a number, which is an `rt.Place`. */ +export function tally$Shape(self: Hits, sum: rt.Place): void { + sum.v = rt.u32WrappingAdd(sum.v, area$Shape(self)); +} + +/** Counts its calls, which every `Arc` of it sees. */ +export interface Hits { + _0: rt.Atomic; +} + +export function area$Shape(self: Hits): rt.u32 { + return rt.atomicFetch(self._0, rt.u32WrappingAdd, 1, 0); +} + +export function grow$Shape(self: Hits, by: rt.u8): void { + const _3: rt.u32 = rt.u32WrappingAdd(self._0.v, by as rt.u32); + self._0.v = _3; +} + +//# sourceMappingURL=dyns.Hits.ts.map diff --git a/ts/fixtures/lang/expected/dyns.Shape.ts b/ts/fixtures/lang/expected/dyns.Shape.ts index d0c9ff9d7..b7e418b55 100644 --- a/ts/fixtures/lang/expected/dyns.Shape.ts +++ b/ts/fixtures/lang/expected/dyns.Shape.ts @@ -2,9 +2,42 @@ import * as rt from "./rt.ts"; import { sides$Shape_u32, intoArea$Shape_u32, larger$Shape_u32, tally$Shape_u32, area$Shape_u32, grow$Shape_u32 } from "./dyns.ts"; +import * as dyns_Hits from "./dyns.Hits.ts"; import * as dyns_Square from "./dyns.Square.ts"; import * as dyns_Tri from "./dyns.Tri.ts"; +export class Hits { + v: dyns_Hits.Hits; + + constructor(v: dyns_Hits.Hits) { + this.v = v; + } + + area$Shape(): rt.u32 { + return dyns_Hits.area$Shape(this.v); + } + + grow$Shape(a: rt.u8): void { + return dyns_Hits.grow$Shape(this.v, a); + } + + intoArea$Shape(): rt.u32 { + return dyns_Hits.intoArea$Shape(this.v); + } + + larger$Shape(a: rt.u32): rt.u32 { + return dyns_Hits.larger$Shape(this.v, a); + } + + sides$Shape(): rt.u8 { + return dyns_Hits.sides$Shape(this.v); + } + + tally$Shape(a: rt.Place): void { + return dyns_Hits.tally$Shape(this.v, a); + } +} + export type Shape = | { area$Shape: () => rt.u32; grow$Shape: (a0: rt.u8) => void; sides$Shape: () => rt.u8; intoArea$Shape: () => rt.u32; larger$Shape: (a0: rt.u32) => rt.u32; tally$Shape: (a0: rt.Place) => void }; diff --git a/ts/fixtures/lang/expected/dyns.ts b/ts/fixtures/lang/expected/dyns.ts index 0b9815e7f..fd47e82d5 100644 --- a/ts/fixtures/lang/expected/dyns.ts +++ b/ts/fixtures/lang/expected/dyns.ts @@ -1,6 +1,8 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { map$Option_Arc_dyn_Shape_u32_shared_closure0 } from "./core/option.ts"; +import type * as Hits from "./dyns.Hits.ts"; import * as Named from "./dyns.Named.ts"; import * as Shape from "./dyns.Shape.ts"; import * as Shown from "./dyns.Shown.ts"; @@ -194,4 +196,471 @@ export function dyns(data: rt.ByteSlice, out: rt.ByteVec): void { } } +export function counts$Hits(arcs: rt.Arc[]): string { + return rt.iterToArray(rt.iterMap(rt.iterSlice(arcs), (a: rt.Arc): string => { + const _42: rt.usize = a.strong; + return rt.fmtToString((f: rt.Formatter) => rt.usizeDisplay(_42, f)); + })).join(","); +} + +export function counts$Square(arcs: rt.Arc[]): string { + return rt.iterToArray(rt.iterMap(rt.iterSlice(arcs), (a: rt.Arc): string => { + const _42: rt.usize = a.strong; + return rt.fmtToString((f: rt.Formatter) => rt.usizeDisplay(_42, f)); + })).join(","); +} + +export function counts$dyn_Named(arcs: rt.Arc[]): string { + return rt.iterToArray(rt.iterMap(rt.iterSlice(arcs), (a: rt.Arc): string => { + const _42: rt.usize = a.strong; + return rt.fmtToString((f: rt.Formatter) => rt.usizeDisplay(_42, f)); + })).join(","); +} + +export function counts$dyn_Shape(arcs: rt.Arc[]): string { + return rt.iterToArray(rt.iterMap(rt.iterSlice(arcs), (a: rt.Arc): string => { + const _42: rt.usize = a.strong; + return rt.fmtToString((f: rt.Formatter) => rt.usizeDisplay(_42, f)); + })).join(","); +} + +export function shared(data: rt.ByteSlice, out: rt.ByteVec): void { + let sq!: rt.Arc; + let named!: rt.Arc; + let again!: rt.Arc; + let shape!: rt.Arc; + let up!: rt.Arc; + let _168!: rt.Arc | undefined; + let _189!: rt.Arc | undefined; + let hits!: rt.Arc; + let objects!: rt.Arc[]; + let n!: rt.Arc; + let m!: rt.Arc; + let tris!: rt.Arc[]; + let kept!: rt.Arc[]; + let _384!: boolean; + let _385!: boolean; + let _386!: boolean; + let _387!: boolean; + let _388!: boolean; + let _389!: boolean; + let _390!: boolean; + let unwind: number = 0; + try { + _390 = false; + _389 = false; + _388 = false; + _387 = false; + _386 = false; + _385 = false; + _384 = false; + if (data.length >= 2) { + const _9: Square.Square = { side: data.data[data.start] as rt.u16 }; + _390 = true; + sq = new rt.Arc(_9); + unwind = 251; + const _13: rt.Arc = rt.arcClone(sq); + unwind = 239; + _389 = true; + named = new rt.ArcDyn(_13, new Named.Square(_13.value)); + const _16: rt.Arc = rt.arcClone(sq); + unwind = 238; + _388 = true; + again = new rt.ArcDyn(_16, new Named.Square(_16.value)); + const _19: rt.Arc = rt.arcClone(named); + unwind = 237; + _387 = true; + shape = _19; + const _22: rt.Arc = rt.arcClone(again); + unwind = 246; + _386 = true; + up = _22; + const _32: string = counts$Square([sq]); + unwind = 236; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _32)]; + const _28: string = rt.fmtFormat([args2[0], " "]); + unwind = 246; + const _27: string = _28; + unwind = 235; + put(out, _27); + unwind = 246; + const _49: string = named.value.label$Named(); + unwind = 234; + const _53: rt.u32 = shape.value.area$Shape(); + const _57: rt.u8 = sidesOf$dyn_Shape(up.value); + const _62: Named.Named = named.value; + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _49), (f: rt.Formatter) => rt.u32Display(_53, f), (f: rt.Formatter) => rt.u8Display(_57, f), (f: rt.Formatter) => _62.fmt$Debug(f)]; + const _45: string = rt.fmtFormat([args4[0], " ", args4[1], " ", args4[2], " ", args4[3], " "]); + unwind = 246; + const _44: string = _45; + unwind = 233; + put(out, _44); + unwind = 246; + const _74: rt.Weak = new rt.Weak(shape); + unwind = 232; + const _76: rt.Weak = new rt.Weak(up); + unwind = 230; + const weak: rt.Weak = _74; + const other: rt.Weak = _76; + const _86: boolean = rt.arcPtrEq(named, again); + const _90: boolean = rt.arcPtrEq(shape, up); + const _94: boolean = rt.arcPtrEq(weak.arc, other.arc); + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(_86, f), (f: rt.Formatter) => rt.fmtBool(_90, f), (f: rt.Formatter) => rt.fmtBool(_94, f)]; + const _81: string = rt.fmtFormat([args6[0], " ", args6[1], " ", args6[2], " "]); + unwind = 229; + put(out, _81); + unwind = 230; + _390 = false; + rt.drop(sq); + _389 = false; + rt.drop(named); + const _115: string = counts$dyn_Named([again]); + unwind = 228; + const _121: rt.usize = weak.arc.strong; + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _115), (f: rt.Formatter) => rt.usizeDisplay(_121, f)]; + const _111: string = rt.fmtFormat([args8[0], " ", args8[1], " "]); + unwind = 230; + const _110: string = _111; + unwind = 227; + put(out, _110); + unwind = 230; + const upgraded: rt.u32 | undefined = map$Option_Arc_dyn_Shape_u32_shared_closure0(rt.weakUpgrade(weak), (s: rt.Arc): rt.u32 => { + let unwind2: number = 0; + try { + unwind2 = 5; + const _0: rt.u32 = s.value.area$Shape(); + unwind2 = 0; + rt.drop(s); + return _0; + } catch (e2) { + if (unwind2 === 0) { + throw e2; + } + rt.drop(s); + throw e2; + } + }); + _388 = false; + rt.drop(again); + const _141: string = counts$dyn_Shape([up]); + unwind = 226; + const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _141)]; + const _137: string = rt.fmtFormat([args10[0], " "]); + unwind = 230; + const _136: string = _137; + unwind = 225; + put(out, _136); + unwind = 230; + _386 = false; + rt.drop(up); + const _160: string = counts$dyn_Shape([shape]); + unwind = 224; + _168 = rt.weakUpgrade(weak); + unwind = 223; + const _166: boolean = _168 !== undefined; + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _160), (f: rt.Formatter) => rt.fmtBool(_166, f), (f: rt.Formatter) => rt.fmtOption(upgraded, f, rt.u32Debug)]; + const _156: string = rt.fmtFormat([args12[0], " ", args12[1], " ", args12[2], " "]); + unwind = 224; + rt.drop(_168); + unwind = 230; + const _155: string = _156; + unwind = 222; + put(out, _155); + unwind = 230; + _387 = false; + rt.drop(shape); + _189 = rt.weakUpgrade(weak); + unwind = 221; + const _187: boolean = _189 === undefined; + const _192: rt.usize = other.arc.strong; + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(_187, f), (f: rt.Formatter) => rt.usizeDisplay(_192, f)]; + const _183: string = rt.fmtFormat([args14[0], " ", args14[1], " "]); + unwind = 230; + rt.drop(_189); + const _182: string = _183; + unwind = 220; + put(out, _182); + unwind = 230; + hits = new rt.Arc({ _0: new rt.Atomic(data.data[data.start + 1] as rt.u32) }); + unwind = 219; + objects = rt.iterToArray(rt.iterMap(new rt.Range(0, 3), (_2: rt.i32): rt.Arc => { + const _34: rt.Arc = rt.arcClone(hits); + return new rt.ArcDyn(_34, new Shape.Hits(_34.value)); + }), false, undefined, rt.drop); + unwind = 244; + _385 = true; + const sum: rt.u32 = rt.iterFold(rt.iterSlice(objects), 0, (sum2: rt.u32, s2: rt.Arc): rt.u32 => { + return rt.u32WrappingAdd(sum2, s2.value.area$Shape()); + }); + const _221: rt.u32 = rt.atomicLoad(hits.value._0, 0); + const _227: string = counts$Hits([hits]); + unwind = 218; + const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(sum, f), (f: rt.Formatter) => rt.u32Display(_221, f), (f: rt.Formatter) => rt.fmtPad(f, _227)]; + const _217: string = rt.fmtFormat([args16[0], " ", args16[1], " ", args16[2], " "]); + unwind = 244; + const _216: string = _217; + unwind = 217; + put(out, _216); + unwind = 244; + _385 = false; + rt.dropAll(objects); + const _249: string = counts$Hits([hits]); + unwind = 216; + const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _249)]; + const _245: string = rt.fmtFormat([args18[0], " "]); + unwind = 244; + const _244: string = _245; + unwind = 215; + put(out, _244); + unwind = 244; + const _259: rt.Arc = new rt.Arc(data.data[data.start + 1] as rt.u32); + unwind = 214; + n = new rt.ArcDyn(_259, new Shape.u32(_259.value)); + const _263: rt.Arc = new rt.Arc(data.data[data.start + 1] as rt.u32); + unwind = 213; + m = new rt.ArcDyn(_263, new Shape.u32(_263.value)); + const _274: rt.u32 = n.value.area$Shape(); + const _278: boolean = rt.arcPtrEq(n, m); + const args20: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(_274, f), (f: rt.Formatter) => rt.fmtBool(_278, f)]; + const _269: string = rt.fmtFormat([args20[0], " ", args20[1], " "]); + unwind = 212; + put(out, _269); + unwind = 213; + tris = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(new rt.ByteSlice(data.data, data.start + 2, data.length - 2))), (_23: rt.u8): rt.Arc => { + const x: rt.u8 = _23; + const _43: rt.u8 = rt.u8Rem(x, 3); + if (_43 === 0) { + const _72: rt.Arc = new rt.Arc({ tag: "Flat" } as Tri.Tri); + return new rt.ArcDyn(_72, new Named.Tri(_72.value)); + } + if (_43 === 1) { + const _92: rt.Arc = new rt.Arc({ tag: "Tall", _0: x } as Tri.Tri); + return new rt.ArcDyn(_92, new Named.Tri(_92.value)); + } + const _113: rt.Arc = new rt.Arc({ side: x as rt.u16 }); + return new rt.ArcDyn(_113, new Named.Square(_113.value)); + }), false, undefined, rt.drop); + unwind = 242; + _384 = true; + kept = rt.iterToArray(rt.iterMap(rt.iterStepBy(rt.iterSlice(tris), 2), (a0: rt.Arc): rt.Arc => { + return rt.arcClone(a0); + }), false, undefined, rt.drop); + unwind = 211; + for (const _298 of tris) { + const _310: string = _298.value.label$Named(); + unwind = 210; + const _313: rt.u32 = _298.value.area$Shape(); + const _316: rt.usize = _298.strong; + const args22: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _310), (f: rt.Formatter) => rt.u32Display(_313, f), (f: rt.Formatter) => rt.usizeDisplay(_316, f)]; + const _306: string = rt.fmtFormat([args22[0], ":", args22[1], ":", args22[2], " "]); + unwind = 211; + const _305: string = _306; + unwind = 209; + put(out, _305); + } + _384 = false; + rt.dropAll(tris); + let total_: rt.u32 = 0; + for (const _329 of kept) { + _329.value.tally$Shape(rt.place(() => total_, (value) => total_ = value)); + } + const _347: rt.Arc[] = rt.iterToArray(rt.iterSlice(kept)); + unwind = 208; + const _344: string = counts$dyn_Named(_347); + unwind = 207; + const args24: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(total_, f), (f: rt.Formatter) => rt.fmtPad(f, _344)]; + const _340: string = rt.fmtFormat([args24[0], " ", args24[1]]); + unwind = 211; + const _339: string = _340; + unwind = 206; + put(out, _339); + unwind = 242; + rt.dropAll(kept); + unwind = 214; + _384 = false; + rt.drop(m); + unwind = 244; + rt.drop(n); + unwind = 230; + _385 = false; + rt.drop(hits); + _386 = false; + _387 = false; + _388 = false; + _389 = false; + _390 = false; + } + } catch (e) { + b5: { + b6: { + b7: { + b8: { + b9: { + b10: { + b11: { + b12: { + b13: { + b14: { + b15: { + b16: { + b17: { + b18: { + if (unwind === 0) { + throw e; + } + if (unwind === 206) { + break b17; + } + if (unwind === 207) { + break b18; + } + if (unwind === 208) { + break b18; + } + if (unwind === 209) { + break b17; + } + if (unwind === 210) { + break b17; + } + if (unwind === 211) { + break b17; + } + if (unwind === 212) { + break b15; + } + if (unwind === 213) { + break b15; + } + if (unwind === 214) { + break b14; + } + if (unwind === 215) { + break b13; + } + if (unwind === 216) { + break b13; + } + if (unwind === 217) { + break b13; + } + if (unwind === 218) { + break b13; + } + if (unwind === 219) { + break b12; + } + if (unwind === 220) { + break b11; + } + if (unwind === 221) { + rt.drop(_189); + break b11; + } + if (unwind === 222) { + break b11; + } + if (unwind === 223) { + rt.drop(_168); + } else if (unwind !== 224) { + if (unwind === 225) { + break b11; + } + if (unwind === 226) { + break b11; + } + if (unwind === 227) { + break b11; + } + if (unwind === 228) { + break b11; + } + if (unwind === 229) { + break b11; + } + if (unwind === 230) { + break b11; + } + if (unwind === 231) { + break b10; + } + if (unwind === 232) { + break b9; + } + if (unwind === 233) { + break b9; + } + if (unwind === 234) { + break b9; + } + if (unwind === 235) { + break b9; + } + if (unwind === 236) { + break b9; + } + if (unwind === 237) { + break b8; + } + if (unwind === 238) { + break b7; + } + if (unwind === 239) { + break b6; + } + if (unwind === 242) { + break b16; + } + if (unwind === 244) { + break b13; + } + if (unwind === 246) { + break b9; + } + break b5; + } + break b11; + } + } + rt.dropAll(kept); + } + if (_384) { + rt.dropAll(tris); + } + } + rt.drop(m); + } + rt.drop(n); + } + if (_385) { + rt.dropAll(objects); + } + } + rt.drop(hits); + } + } + } + if (_386) { + rt.drop(up); + } + } + if (_387) { + rt.drop(shape); + } + } + if (_388) { + rt.drop(again); + } + } + if (_389) { + rt.drop(named); + } + } + if (_390) { + rt.drop(sq); + } + throw e; + } +} + //# sourceMappingURL=dyns.ts.map diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 09de6221c..c09d484d5 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -9,7 +9,7 @@ import { hashMaps, sets, btreeMaps, deques, vecs, stores } from "./collections.t import { combinators } from "./combinators.ts"; import { cows } from "./cows.ts"; import { durations } from "./durations.ts"; -import { dyns } from "./dyns.ts"; +import { dyns, shared } from "./dyns.ts"; import { edits } from "./edits.ts"; import { floats } from "./floats.ts"; import { ints, strings, derived, written, counts, rounding, panics } from "./fmt.ts"; @@ -78,7 +78,9 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) rounding(out23); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["iters::skips", skips] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["wrappers::wrappers", wrappers] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["edits::edits", edits] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["utf8::decodes", decodes] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["floats::floats", floats] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["atomics::atomics", atomics] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["keys::overrides", overrides] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["dyns::dyns", (_233: rt.u8, data23: rt.ByteSlice, out24: rt.ByteVec): void => { dyns(data23, out24); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["cells::cells", cells] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void]]; + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["cells::cells", cells] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["dyns::shared", (_234: rt.u8, data24: rt.ByteSlice, out25: rt.ByteVec): void => { + shared(data24, out25); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void]]; } /** Run one case. */ diff --git a/ts/fixtures/lang/src/dyns.rs b/ts/fixtures/lang/src/dyns.rs index 6138edbe5..c1e3ad6af 100644 --- a/ts/fixtures/lang/src/dyns.rs +++ b/ts/fixtures/lang/src/dyns.rs @@ -1,9 +1,12 @@ //! Trait objects of the crate's own traits, behind `&`, `&mut`, and `Box`: each call runs //! the impl of the value's own type, a struct, an enum, or a number, changing it in place //! through `&mut self` wherever it is, a provided method, a supertrait's, `Debug` among -//! them, `self: Box`, and an upcast to the supertrait. +//! them, `self: Box`, and an upcast to the supertrait. Behind an `Arc`, the object +//! shares the count of the `Arc` it was made from. use std::fmt::{self, Debug}; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Weak}; use crate::fmt::put; @@ -178,3 +181,99 @@ pub fn dyns(data: &[u8], out: &mut Vec) { let boxed: Box = Box::new(n); put(out, &format!("{sum} {}", boxed.into_area())); } + +/// Counts its calls, which every `Arc` of it sees. +struct Hits(AtomicU32); + +impl Shape for Hits { + fn area(&self) -> u32 { + self.0.fetch_add(1, Ordering::Relaxed) + } + fn grow(&mut self, by: u8) { + *self.0.get_mut() = self.0.get_mut().wrapping_add(u32::from(by)); + } +} + +fn counts(arcs: &[&Arc]) -> String { + let counts: Vec = arcs.iter().map(|a| Arc::strong_count(a).to_string()).collect(); + counts.join(",") +} + +pub fn shared(data: &[u8], out: &mut Vec) { + let [a, b, rest @ ..] = data else { + return; + }; + + // Two objects of one `Arc`, and an upcast of each: one count, which either side's + // clones and drops change, and one value. + let sq = Arc::new(Square { side: u16::from(*a) }); + let named: Arc = sq.clone(); + let again: Arc = Arc::::clone(&sq); + let shape: Arc = named.clone(); + let up: Arc = again.clone(); + put(out, &format!("{} ", counts(&[&sq]))); + put( + out, + &format!("{} {} {} {:?} ", named.label(), shape.area(), sides_of(&*up), &*named), + ); + let (weak, other) = (Arc::downgrade(&shape), Arc::downgrade(&up)); + put( + out, + &format!( + "{} {} {} ", + Arc::ptr_eq(&named, &again), + Arc::ptr_eq(&shape, &up), + Weak::ptr_eq(&weak, &other) + ), + ); + drop(sq); + drop(named); + put(out, &format!("{} {} ", counts(&[&again]), Weak::strong_count(&weak))); + let upgraded = weak.upgrade().map(|s| s.area()); + drop(again); + put(out, &format!("{} ", counts(&[&up]))); + drop(up); + put( + out, + &format!("{} {} {:?} ", counts(&[&shape]), weak.upgrade().is_some(), upgraded), + ); + drop(shape); + put( + out, + &format!("{} {} ", weak.upgrade().is_none(), Weak::strong_count(&other)), + ); + + // Calls through every `Arc` reach the one value. + let hits = Arc::new(Hits(AtomicU32::new(u32::from(*b)))); + let objects: Vec> = (0..3).map(|_| hits.clone() as Arc).collect(); + let sum = objects.iter().fold(0u32, |sum, s| sum.wrapping_add(s.area())); + put( + out, + &format!("{sum} {} {} ", hits.0.load(Ordering::Relaxed), counts(&[&hits])), + ); + drop(objects); + put(out, &format!("{} ", counts(&[&hits]))); + + // Of a number and an enum, which JS copies, and two `Arc`s that are not the same. + let n: Arc = Arc::new(u32::from(*b)); + let m: Arc = Arc::new(u32::from(*b)); + put(out, &format!("{} {} ", n.area(), Arc::ptr_eq(&n, &m))); + let tris: Vec> = rest + .iter() + .map(|&x| match x % 3 { + 0 => Arc::new(Tri::Flat) as Arc, + 1 => Arc::new(Tri::Tall(x)), + _ => Arc::new(Square { side: u16::from(x) }), + }) + .collect(); + let kept: Vec> = tris.iter().step_by(2).cloned().collect(); + for t in &tris { + put(out, &format!("{}:{}:{} ", t.label(), t.area(), Arc::strong_count(t))); + } + drop(tris); + let mut total = 0u32; + for k in &kept { + k.tally(&mut total); + } + put(out, &format!("{total} {}", counts(&kept.iter().collect::>()))); +} diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 5003c3924..7b65f8411 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -85,6 +85,7 @@ fn cases() -> Vec<(&'static str, Case)> { ("keys::overrides", keys::overrides), ("dyns::dyns", |_, data, out| dyns::dyns(data, out)), ("cells::cells", cells::cells), + ("dyns::shared", |_, data, out| dyns::shared(data, out)), ] } diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index d1cb2b603..e32b84640 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 76 -- Function instances: 84 +- Refusals: 75 +- Function instances: 83 - Generic functions no instance reached, lowered over their type parameters: 6 ## By construct @@ -17,9 +17,8 @@ | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | fixtures/reject/src/lib.rs:16:15 | | 2 | `_` of `_`, whose `None` is `rt.None`, which is not supported yet | fixtures/reject/src/lib.rs:41:42 | | 2 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | fixtures/reject/src/lib.rs:261:16 | -| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | fixtures/reject/src/lib.rs:503:23 | -| 2 | a coercion to `_` | fixtures/reject/src/lib.rs:355:2 | -| 2 | a coercion to `_`, which is not supported yet | fixtures/reject/src/lib.rs:494:39 | +| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | fixtures/reject/src/lib.rs:488:23 | +| 2 | a coercion to `_`, which is not supported yet | fixtures/reject/src/lib.rs:479:40 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:168:1 | | 2 | constructing `_` from another crate | fixtures/reject/src/lib.rs:154:23 | | 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:148:2 | @@ -38,13 +37,14 @@ | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | fixtures/reject/src/lib.rs:235:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | fixtures/reject/src/lib.rs:181:51 | | 1 | a cast from `_` to `_` | fixtures/reject/src/lib.rs:105:2 | +| 1 | a coercion to `_` | fixtures/reject/src/lib.rs:355:2 | | 1 | a constant of type `_` | fixtures/reject/src/lib.rs:89:2 | | 1 | a copy of a closure that changes what it captured | fixtures/reject/src/lib.rs:271:14 | | 1 | a mutable borrow of a subslice of `_`, which JS would copy, having no views | fixtures/reject/src/lib.rs:240:13 | | 1 | a mutable reference into a `Result`'s payload, passed on or kept | fixtures/reject/src/lib.rs:427:12 | | 1 | a printable type must implement `Display` or `Debug` | fixtures/reject/src/lib.rs:101:1 | | 1 | a scalar constant of type `_` | fixtures/reject/src/lib.rs:8:2 | -| 1 | a trait object of `_`, which is not supported yet | fixtures/reject/src/lib.rs:520:26 | +| 1 | a trait object of `_`, which is not supported yet | fixtures/reject/src/lib.rs:505:26 | | 1 | a zero-sized constant of type `_` | fixtures/reject/src/lib.rs:71:2 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:8:2 | | 1 | collecting `_`, whose `None` is `rt.None`, which is not supported yet | fixtures/reject/src/lib.rs:36:43 | @@ -63,17 +63,17 @@ The type or module each refused type or path belongs to. | 7 | `std::borrow::Cow` | fixtures/reject/src/lib.rs:396:2 | | 6 | `Option` | fixtures/reject/src/lib.rs:16:15 | | 6 | `f32` | fixtures/reject/src/lib.rs:7:14 | -| 5 | `std::sync::Arc` | fixtures/reject/src/lib.rs:110:2 | | 4 | `Iterator` | fixtures/reject/src/lib.rs:41:42 | | 3 | `std::iter::Map` | fixtures/reject/src/lib.rs:56:23 | +| 3 | `std::sync::Arc` | fixtures/reject/src/lib.rs:110:2 | | 3 | `std::vec::Vec` | fixtures/reject/src/lib.rs:282:52 | | 3 | `u8` | fixtures/reject/src/lib.rs:89:2 | | 3 | `{closure}` | fixtures/reject/src/lib.rs:383:13 | | 2 | `HashMap` | fixtures/reject/src/lib.rs:277:6 | | 2 | `Meters` | fixtures/reject/src/lib.rs:94:2 | | 2 | `Poll` | fixtures/reject/src/lib.rs:114:20 | -| 2 | `Scaled` | fixtures/reject/src/lib.rs:503:23 | -| 2 | `dyn Scaled` | fixtures/reject/src/lib.rs:503:23 | +| 2 | `Scaled` | fixtures/reject/src/lib.rs:488:23 | +| 2 | `dyn Scaled` | fixtures/reject/src/lib.rs:488:23 | | 2 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:62:13 | | 2 | `std::iter::Iterator` | fixtures/reject/src/lib.rs:261:16 | | 2 | `std::ops::Range` | fixtures/reject/src/lib.rs:189:8 | @@ -88,9 +88,9 @@ The type or module each refused type or path belongs to. | 1 | `Maybe` | fixtures/reject/src/lib.rs:31:2 | | 1 | `Noisy` | fixtures/reject/src/lib.rs:62:13 | | 1 | `T \| undefined` | fixtures/reject/src/lib.rs:31:2 | -| 1 | `Tail` | fixtures/reject/src/lib.rs:530:30 | +| 1 | `Tail` | fixtures/reject/src/lib.rs:515:30 | | 1 | `[u16; 1]` | fixtures/reject/src/lib.rs:254:22 | -| 1 | `[u8; 4]` | fixtures/reject/src/lib.rs:520:26 | +| 1 | `[u8; 4]` | fixtures/reject/src/lib.rs:505:26 | | 1 | `count` | fixtures/reject/src/lib.rs:56:23 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:11:16 | | 1 | `f64` | fixtures/reject/src/lib.rs:463:2 | @@ -102,6 +102,7 @@ The type or module each refused type or path belongs to. | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:135:11 | | 1 | `std::string::String` | fixtures/reject/src/lib.rs:83:10 | | 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:130:2 | +| 1 | `std::sync::Weak` | fixtures/reject/src/lib.rs:479:40 | | 1 | `str` | fixtures/reject/src/lib.rs:391:4 | | 1 | `u32` | fixtures/reject/src/lib.rs:240:13 | | 1 | `u64` | fixtures/reject/src/lib.rs:105:2 | @@ -116,8 +117,7 @@ The type or module each refused type or path belongs to. | 3 | unsupported type `_` | `f32` | fixtures/reject/src/lib.rs:7:14 | | 2 | `_` is not supported: it would be pending two ways with one value | `Poll` | fixtures/reject/src/lib.rs:114:20 | | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | `Option` | fixtures/reject/src/lib.rs:16:15 | -| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | `dyn Scaled`, `Scaled` | fixtures/reject/src/lib.rs:503:23 | -| 2 | a coercion to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:355:2 | +| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | `dyn Scaled`, `Scaled` | fixtures/reject/src/lib.rs:488:23 | | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:125:2 | | 2 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:94:2 | | 2 | unsupported call to `_` | `::sum` | fixtures/reject/src/lib.rs:453:17 | @@ -137,12 +137,13 @@ The type or module each refused type or path belongs to. | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | `std::iter::Map`, `std::ops::Range` | fixtures/reject/src/lib.rs:235:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | `std::iter::Chain` | fixtures/reject/src/lib.rs:181:51 | | 1 | a cast from `_` to `_` | `u64`, `f32` | fixtures/reject/src/lib.rs:105:2 | -| 1 | a coercion to `_`, which is not supported yet | `&Tail` | fixtures/reject/src/lib.rs:530:30 | -| 1 | a coercion to `_`, which is not supported yet | `std::sync::Arc` | fixtures/reject/src/lib.rs:494:39 | +| 1 | a coercion to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:355:2 | +| 1 | a coercion to `_`, which is not supported yet | `&Tail` | fixtures/reject/src/lib.rs:515:30 | +| 1 | a coercion to `_`, which is not supported yet | `std::sync::Weak` | fixtures/reject/src/lib.rs:479:40 | | 1 | a constant of type `_` | `&u8` | fixtures/reject/src/lib.rs:89:2 | | 1 | a mutable borrow of a subslice of `_`, which JS would copy, having no views | `u32` | fixtures/reject/src/lib.rs:240:13 | | 1 | a scalar constant of type `_` | `f32` | fixtures/reject/src/lib.rs:8:2 | -| 1 | a trait object of `_`, which is not supported yet | `[u8; 4]` | fixtures/reject/src/lib.rs:520:26 | +| 1 | a trait object of `_`, which is not supported yet | `[u8; 4]` | fixtures/reject/src/lib.rs:505:26 | | 1 | a zero-sized constant of type `_` | `{async closure}` | fixtures/reject/src/lib.rs:71:2 | | 1 | an assignment through a reference to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:110:2 | | 1 | an assignment through a reference to `_` | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:130:2 | @@ -254,22 +255,15 @@ The type or module each refused type or path belongs to.
`_`, a trait object of the generic trait `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:503:23: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet -- fixtures/reject/src/lib.rs:504:4: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet - -
- -
a coercion to `_` (2) - -- fixtures/reject/src/lib.rs:355:2: a coercion to `std::sync::Arc<[u8]>` -- fixtures/reject/src/lib.rs:469:2: a coercion to `std::sync::Arc>` +- fixtures/reject/src/lib.rs:488:23: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet +- fixtures/reject/src/lib.rs:489:4: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet
a coercion to `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:494:39: a coercion to `std::sync::Arc`, which is not supported yet -- fixtures/reject/src/lib.rs:530:30: a coercion to `&Tail`, which is not supported yet +- fixtures/reject/src/lib.rs:479:40: a coercion to `std::sync::Weak`, which is not supported yet +- fixtures/reject/src/lib.rs:515:30: a coercion to `&Tail`, which is not supported yet
@@ -385,6 +379,12 @@ The type or module each refused type or path belongs to. +
a coercion to `_` (1) + +- fixtures/reject/src/lib.rs:355:2: a coercion to `std::sync::Arc<[u8]>` + +
+
a constant of type `_` (1) - fixtures/reject/src/lib.rs:89:2: a constant of type `&u8` @@ -423,7 +423,7 @@ The type or module each refused type or path belongs to.
a trait object of `_`, which is not supported yet (1) -- fixtures/reject/src/lib.rs:520:26: a trait object of `[u8; 4]`, which is not supported yet +- fixtures/reject/src/lib.rs:505:26: a trait object of `[u8; 4]`, which is not supported yet
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 892d2bc96..cfd0e5b5e 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -24,7 +24,6 @@ replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs an assignment through a reference to `std::sync::Arc` at fixtures/reject/src/lib.rs:110:2 `Poll>>` is not supported: it would be pending two ways with one value at fixtures/reject/src/lib.rs:114:20 `Poll>` is not supported: it would be pending two ways with one value at fixtures/reject/src/lib.rs:119:54 -a coercion to `std::sync::Arc>` at fixtures/reject/src/lib.rs:469:2 an assignment through a reference to `std::pin::Pin>` at fixtures/reject/src/lib.rs:125:2 an assignment through a reference to `std::sync::MutexGuard<'_, u8>` at fixtures/reject/src/lib.rs:130:2 unsupported call to ` as std::iter::Iterator>::cycle` at fixtures/reject/src/lib.rs:135:11 @@ -63,11 +62,11 @@ a mutable reference into a `Result`'s payload, passed on or kept at fixtures/rej unsupported call to ` as std::cmp::PartialEq>::eq` at fixtures/reject/src/lib.rs:434:2 `f64::mul_add`, which rounds once, where JS would round twice at fixtures/reject/src/lib.rs:458:4 unsupported call to `::fmt` at fixtures/reject/src/lib.rs:463:11 -a coercion to `std::sync::Arc`, which is not supported yet at fixtures/reject/src/lib.rs:494:39 -`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:503:23 -`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:504:4 -a trait object of `[u8; 4]`, which is not supported yet at fixtures/reject/src/lib.rs:520:26 -a coercion to `&Tail`, which is not supported yet at fixtures/reject/src/lib.rs:530:30 +a coercion to `std::sync::Weak`, which is not supported yet at fixtures/reject/src/lib.rs:479:40 +`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:488:23 +`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:489:4 +a trait object of `[u8; 4]`, which is not supported yet at fixtures/reject/src/lib.rs:505:26 +a coercion to `&Tail`, which is not supported yet at fixtures/reject/src/lib.rs:515:30 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:148:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:168:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:202:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 956f39b04..74ce254eb 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -463,22 +463,6 @@ pub fn float_printed(a: f64) -> String { format!("{a}") } -/// An `Arc` around a future of the crate's: a `dyn Future` behind it would need the `Arc`'s -/// own count around an `rt.Future`. -pub fn shared_future() -> std::sync::Arc> { - std::sync::Arc::new(Ready(1)) -} - -pub struct Ready(u8); - -impl std::future::Future for Ready { - type Output = u8; - - fn poll(self: std::pin::Pin<&mut Self>, _: &mut std::task::Context<'_>) -> std::task::Poll { - std::task::Poll::Ready(self.0) - } -} - pub trait Reading { fn read(&self) -> u8; } @@ -489,10 +473,11 @@ impl Reading for u8 { } } -/// An `Arc` of a trait object, whose count the `Arc` it was made from shares. -pub fn shared_object(n: u8) -> u8 { - let r: std::sync::Arc = std::sync::Arc::new(n); - r.read() +/// A `Weak` of a trait object, which would need an object made of a value that may be +/// gone. +pub fn weak_object(n: std::sync::Weak) -> Option { + let r: std::sync::Weak = n; + r.upgrade().map(|r| r.read()) } pub trait Scaled { diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index dd7c74f31..7216d83ce 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -20,7 +20,6 @@ roots = [ "replace_shared", "nested_poll", "pending_output", - "shared_future", "replace_pinned", "replace_guard", "cycled", @@ -56,7 +55,7 @@ roots = [ "places_equal", "fma", "float_printed", - "shared_object", + "weak_object", "generic_object", "first_of", "tail_read", diff --git a/ts/fixtures/task/expected/core/option.ts b/ts/fixtures/task/expected/core/option.ts index 6b39f6503..925b01ea7 100644 --- a/ts/fixtures/task/expected/core/option.ts +++ b/ts/fixtures/task/expected/core/option.ts @@ -86,6 +86,13 @@ export function map$Option_u32_u32_discarded_closure16(self: rt.u32 | undefined, return _0; } +export function mapOr$Option_Arc_dyn_Part_u32_shared_closure4(self: rt.Arc | undefined, default_: rt.u32, f: (a0: rt.Arc) => rt.u32): rt.u32 { + if (self === undefined) { + return default_; + } + return f(self); +} + export function mapOr$Option_Box_dyn_Part_u32_boxed_closure3(self: Part.Part | undefined, default_: rt.u32, f: (a0: Part.Part) => rt.u32): rt.u32 { if (self === undefined) { return default_; diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index 04c7fd1a7..ac2e961bc 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -6,7 +6,7 @@ import { isSomeAnd$Option_Guard_options_closure7, unwrapOr$Option_Guard, unwrapO import { ok$Result_Guard_Guard, err$Result_Guard_Guard, asRef$Result_Guard_u8, mapOr$Result_Guard_u8_u32_id, mapOrElse$Result_Guard_Guard_u32_options_closure9_options_closure10, inspectErr$Result_u8_Key_tripped_closure6, andThen$Result_Guard_Guard_Guard_options_closure8, unwrapOr$Result_Guard_Guard } from "./core/result.ts"; import { scoped, discarded, iterated, blasted } from "./drops/closures.ts"; import { looped, collected, drained, extended, bombed, spent } from "./drops/iters.ts"; -import { boxed } from "./drops/objects.ts"; +import { boxed, shared } from "./drops/objects.ts"; import { run as once_run } from "./drops/once.ts"; import * as Bomb from "./drops.Bomb.ts"; import * as Entries from "./drops.Entries.ts"; @@ -23,9 +23,17 @@ import type * as Consumer from "./kio.Consumer.ts"; import * as Log from "./log.Log.ts"; import * as Guard from "./model.Guard.ts"; -/** What boxed trait objects drop, panicking at the point `at` names, if any. */ -export function dyns(log: Log.Log, id: rt.u32, at: rt.u8): void { - boxed(log, id, at); +/** + * Run trait object scenario `arg % 12`, boxed or shared, panicking at the point + * `arg % 6` names, if any. + */ +export function dyns(log: Log.Log, id: rt.u32, arg: rt.u8): void { + const at: rt.u8 = rt.u8Rem(arg, 6); + if (rt.u8Rem(rt.u8Div(arg, 6), 2) === 0) { + boxed(log, id, at); + } else { + shared(log, id, at); + } } /** Run one-time cells' scenario `at`. */ @@ -42,7 +50,7 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { let v!: Held.Held[]; let _29!: Guard.Guard; let arc!: rt.Arc; - let shared!: rt.Arc; + let shared_!: rt.Arc; let cloned!: rt.Arc; let mutex!: rt.Mutex; let v2!: Held.Held[]; @@ -163,15 +171,15 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { arc = new rt.Arc({ tag: "One", _0: guard(4) } as Held.Held); unwind = 239; _386 = true; - shared = rt.arcClone(arc); + shared_ = rt.arcClone(arc); unwind = 217; _386 = false; rt.arcDrop(arc, drop$Held); - const part4 = shared.strong; + const part4 = shared_.strong; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part4, f)]; Log.note(log, rt.fmtFormat(["arc ", args2[0]])); - const part5 = shared.strong; - cloned = rt.arcClone(shared); + const part5 = shared_.strong; + cloned = rt.arcClone(shared_); unwind = 237; _385 = true; const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part5, f)]; @@ -214,7 +222,7 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { _383 = false; _384 = false; _385 = false; - rt.arcDrop(shared, drop$Held); + rt.arcDrop(shared_, drop$Held); unwind = 0; _386 = false; rt.dropAll(held_, drop$Held); @@ -553,7 +561,7 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { rt.arcDrop(cloned, drop$Held); } } - rt.arcDrop(shared, drop$Held); + rt.arcDrop(shared_, drop$Held); } if (_386) { rt.arcDrop(arc, drop$Held); diff --git a/ts/fixtures/task/expected/drops/objects.ts b/ts/fixtures/task/expected/drops/objects.ts index c152bb80b..8ecfbe638 100644 --- a/ts/fixtures/task/expected/drops/objects.ts +++ b/ts/fixtures/task/expected/drops/objects.ts @@ -1,7 +1,8 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; -import { map$Option_Box_dyn_Part_u32_take, mapOr$Option_Box_dyn_Part_u32_boxed_closure3 } from "../core/option.ts"; +import { drop$Held } from "../lib.ts"; +import { map$Option_Box_dyn_Part_u32_take, mapOr$Option_Arc_dyn_Part_u32_shared_closure4, mapOr$Option_Box_dyn_Part_u32_boxed_closure3 } from "../core/option.ts"; import * as Part from "../drops/objects.Part.ts"; import * as Bomb from "../drops.Bomb.ts"; import type * as Held from "../drops.Held.ts"; @@ -152,4 +153,281 @@ export function boxed(log: Log.Log, id: rt.u32, at: rt.u8): void { } } +/** + * Shared parts of each kind, panicking at point `at`, if any, or in a `Drop` at 5, which + * the last `Arc` of it runs, a trait object's, while others still drop. + */ +export function shared(log: Log.Log, id: rt.u32, at: rt.u8): void { + let held!: rt.Arc; + let _11!: Guard.Guard; + let first!: rt.Arc; + let second!: rt.Arc; + let kept!: rt.Arc; + let bomb!: rt.Arc; + let parts!: rt.Arc[]; + let _138!: rt.Arc | undefined; + let future!: rt.Arc>; + let other!: rt.Arc>; + let _181!: boolean; + let _182!: boolean; + let _183!: boolean; + let _184!: boolean; + let _185!: boolean; + let _186!: boolean; + let _187!: boolean; + let _188!: boolean; + let unwind: number = 0; + try { + _188 = false; + _187 = false; + _186 = false; + _185 = false; + _184 = false; + _183 = false; + _182 = false; + _181 = false; + const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { + return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); + }; + const check: (a0: rt.u8) => void = (point: rt.u8): void => { + if (point === at) { + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args14[0], " at ", args14[1]]); + } + }; + _11 = guard(1); + unwind = 88; + const _14: Guard.Guard = guard(2); + unwind = 0; + held = new rt.Arc({ tag: "Two", _0: _11, _1: _14 } as Held.Held); + unwind = 103; + _188 = true; + const _18: rt.Arc = rt.arcClone(held); + unwind = 87; + _187 = true; + first = new rt.ArcDyn(_18, new Part.Held(_18.value)); + const _21: rt.Arc = rt.arcClone(held); + unwind = 100; + _186 = true; + second = new rt.ArcDyn(_21, new Part.Held(_21.value)); + const _29: rt.u32 = first.value.id$Part(); + const _33: rt.usize = held.strong; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(_29, f), (f: rt.Formatter) => rt.usizeDisplay(_33, f)]; + Log.note(log, rt.fmtFormat(["held ", args2[0], " ", args2[1]])); + _188 = false; + rt.arcDrop(held, drop$Held); + check(1); + _187 = false; + rt.drop(first); + const part = second.strong; + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part, f)]; + Log.note(log, rt.fmtFormat(["count ", args4[0]])); + kept = new rt.Arc(guard(3)); + unwind = 98; + _185 = true; + bomb = new rt.Arc(new Bomb.Bomb({ id: rt.u32Add(id, 4), log: Log.clone$Clone(log), blows: at === 5 })); + unwind = 96; + _184 = true; + parts = []; + unwind = 94; + _183 = true; + const _73: rt.Arc = rt.arcClone(bomb); + parts.push(new rt.ArcDyn(_73, new Part.Bomb(_73.value))); + const _78: rt.Arc = rt.arcClone(kept); + parts.push(new rt.ArcDyn(_78, new Part.Guard(_78.value))); + const _82: rt.Arc = rt.arcClone(second); + parts.push(_82); + const _87: rt.Arc = new rt.Arc(7); + parts.push(new rt.ArcDyn(_87, new Part.u32(_87.value))); + const weak: rt.Weak = new rt.Weak(parts[rt.idx(parts, 1)]); + unwind = 86; + check(2); + _186 = false; + rt.drop(second); + const part2 = rt.iterFold(rt.iterMap(rt.iterSlice(parts), (p: rt.Arc): rt.u32 => { + return p.value.id$Part(); + }), 0, (a0: rt.u32, a1: rt.u32): rt.u32 => { + return rt.u32WrappingAdd(a0, a1); + }); + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part2, f)]; + Log.note(log, rt.fmtFormat(["ids ", args6[0]])); + _184 = false; + rt.drop(bomb); + _183 = false; + rt.dropAll(parts); + const part3 = mapOr$Option_Arc_dyn_Part_u32_shared_closure4(rt.weakUpgrade(weak), 0, (p2: rt.Arc): rt.u32 => { + let unwind2: number = 0; + try { + unwind2 = 5; + const _03: rt.u32 = p2.value.id$Part(); + unwind2 = 0; + rt.drop(p2); + return _03; + } catch (e2) { + if (unwind2 === 0) { + throw e2; + } + rt.drop(p2); + throw e2; + } + }); + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part3, f)]; + Log.note(log, rt.fmtFormat(["weak ", args8[0]])); + _185 = false; + rt.drop(kept); + _138 = rt.weakUpgrade(weak); + unwind = 85; + const part4 = _138 === undefined; + const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(part4, f)]; + const _132: string = rt.fmtFormat(["gone ", args10[0]]); + unwind = 86; + rt.drop(_138); + Log.note(log, _132); + const _148: rt.Arc> = new rt.Arc(new sharedFuture(guard(6))); + unwind = 84; + _182 = true; + future = new rt.ArcDyn(_148, _148.value); + other = rt.arcClone(future); + unwind = 91; + _181 = true; + check(3); + _182 = false; + rt.drop(future); + const part5 = other.strong; + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part5, f)]; + Log.note(log, rt.fmtFormat(["future ", args12[0]])); + check(4); + _181 = false; + rt.drop(other); + _181 = false; + _182 = false; + _183 = false; + _184 = false; + _185 = false; + _186 = false; + _187 = false; + _188 = false; + } catch (e) { + b0: { + b1: { + b2: { + b3: { + b4: { + b5: { + b6: { + b7: { + if (unwind === 0) { + throw e; + } + if (unwind !== 84) { + if (unwind === 85) { + rt.drop(_138); + break b7; + } + if (unwind === 86) { + break b7; + } + if (unwind === 87) { + break b2; + } + if (unwind === 88) { + rt.drop(_11); + break b0; + } + if (unwind === 91) { + if (_181) { + rt.drop(other); + } + } else { + if (unwind === 94) { + break b6; + } + if (unwind === 96) { + break b5; + } + if (unwind === 98) { + break b4; + } + if (unwind === 100) { + break b3; + } + break b1; + } + } + if (_182) { + rt.drop(future); + } + } + } + if (_183) { + rt.dropAll(parts); + } + } + if (_184) { + rt.drop(bomb); + } + } + if (_185) { + rt.drop(kept); + } + } + if (_186) { + rt.drop(second); + } + } + if (_187) { + rt.drop(first); + } + } + if (_188) { + rt.arcDrop(held, drop$Held); + } + } + throw e; + } +} + +export class sharedFuture { + #state: number = 0; + #captured: Guard.Guard; + + constructor(captured: Guard.Guard) { + this.#captured = captured; + } + + [Symbol.dispose](): void { + if (this.#state === 0) { + rt.drop(this.#captured); + } + } + + poll(_2: rt.Context): rt.Poll { + let unwind: number = 0; + try { + if (this.#state === 0) { + unwind = 4; + const _4: rt.u32 = Guard.id(this.#captured); + unwind = 5; + rt.drop(this.#captured); + this.#state = 1; + return _4; + } + if (this.#state === 1) { + rt.asyncFnResumed(); + } else { + rt.asyncFnResumedPanic(); + } + } catch (e) { + if (unwind === 0) { + throw e; + } + if (unwind === 4) { + rt.drop(this.#captured); + } + this.#state = 2; + throw e; + } + } +} + //# sourceMappingURL=objects.ts.map diff --git a/ts/fixtures/task/src/drops.rs b/ts/fixtures/task/src/drops.rs index 942364ba7..9e71096d1 100644 --- a/ts/fixtures/task/src/drops.rs +++ b/ts/fixtures/task/src/drops.rs @@ -66,9 +66,14 @@ pub struct Named<'a>(Text<'a>); /// order, the second after the first panics. pub struct Entries(Vec<(K, V)>); -/// What boxed trait objects drop, panicking at the point `at` names, if any. -pub fn dyns(log: &Log, id: u32, at: u8) { - objects::boxed(log, id, at) +/// Run trait object scenario `arg % 12`, boxed or shared, panicking at the point +/// `arg % 6` names, if any. +pub fn dyns(log: &Log, id: u32, arg: u8) { + let at = arg % 6; + match arg / 6 % 2 { + 0 => objects::boxed(log, id, at), + _ => objects::shared(log, id, at), + } } /// Run one-time cells' scenario `at`. diff --git a/ts/fixtures/task/src/drops/objects.rs b/ts/fixtures/task/src/drops/objects.rs index 76a812955..996359e9a 100644 --- a/ts/fixtures/task/src/drops/objects.rs +++ b/ts/fixtures/task/src/drops/objects.rs @@ -1,6 +1,10 @@ //! What a `Box` drops: the value it was made of, by its own type's drop, a //! struct's, an enum's glue, or nothing for a number, where the box goes out of scope, -//! is replaced, or is consumed by `self: Box`, a panic included. +//! is replaced, or is consumed by `self: Box`, a panic included. An `Arc` +//! drops it with the last `Arc` of it, of the trait object or of the type it was made of. + +use std::future::Future; +use std::sync::Arc; use super::{Bomb, Held}; use crate::log::Log; @@ -87,3 +91,55 @@ pub(super) fn boxed(log: &Log, id: u32, at: u8) { check(4); log.note(format!("kept {} {}", kept.as_ref().map_or(0, |p| p.id()), slot.id())); } + +/// Shared parts of each kind, panicking at point `at`, if any, or in a `Drop` at 5, which +/// the last `Arc` of it runs, a trait object's, while others still drop. +pub(super) fn shared(log: &Log, id: u32, at: u8) { + let guard = |n: u32| Guard::new(id + n, log.clone()); + let check = |point: u8| { + if point == at { + panic!("d{id} at {point}"); + } + }; + let held = Arc::new(Held::Two(guard(1), guard(2))); + let first: Arc = held.clone(); + let second: Arc = held.clone(); + log.note(format!("held {} {}", first.id(), Arc::strong_count(&held))); + drop(held); + check(1); + drop(first); + log.note(format!("count {}", Arc::strong_count(&second))); + let kept = Arc::new(guard(3)); + let bomb = Arc::new(Bomb { + id: id + 4, + log: log.clone(), + blows: at == 5, + }); + let mut parts: Vec> = Vec::new(); + parts.push(bomb.clone()); + parts.push(kept.clone()); + parts.push(second.clone()); + parts.push(Arc::new(7u32)); + let weak = Arc::downgrade(&parts[1]); + check(2); + drop(second); + log.note(format!( + "ids {}", + parts.iter().map(|p| p.id()).fold(0u32, u32::wrapping_add) + )); + // The bomb's last `Arc` is the trait object the `Vec` holds; the guard's is its own. + drop(bomb); + drop(parts); + log.note(format!("weak {}", weak.upgrade().map_or(0, |p| p.id()))); + drop(kept); + log.note(format!("gone {}", weak.upgrade().is_none())); + // A future, which drops what it captured with its last `Arc`. + let captured = guard(6); + let future: Arc> = Arc::new(async move { captured.id() }); + let other = future.clone(); + check(3); + drop(future); + log.note(format!("future {}", Arc::strong_count(&other))); + check(4); + drop(other); +} diff --git a/ts/fixtures/task/src/harness.rs b/ts/fixtures/task/src/harness.rs index d26d7edb3..197d3c39e 100644 --- a/ts/fixtures/task/src/harness.rs +++ b/ts/fixtures/task/src/harness.rs @@ -134,7 +134,7 @@ fn steps() -> Vec<(&'static str, Step)> { } }), ("dyns", |log, exec, _, arg| { - drops::dyns(log, 1000 * exec.len() as u32, arg % 6) + drops::dyns(log, 1000 * exec.len() as u32, arg) }), ("cells", |log, exec, _, arg| { drops::cells(log, 1000 * exec.len() as u32, arg) diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index bf05c135e..cb8477650 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -85,6 +85,42 @@ export class Arc implements Disposable { } } +/** + * `Arc` unsized from `arc`, which it shares one count with, as Rust's one + * allocation does: `value` is the trait object over `arc`'s value, which the last of + * either drops. + */ +export class ArcDyn implements Disposable { + readonly arc: Arc; + readonly value: U; + + constructor(arc: Arc, value: U) { + this.arc = arc; + this.value = value; + } + + get strong(): number { + return this.arc.strong; + } + + set strong(strong: number) { + this.arc.strong = strong; + } + + [Symbol.dispose](): void { + if (--this.arc.strong === 0) drop(this.value); + } +} + +/** `Arc::ptr_eq` of trait objects, which compares the `Arc`s they were made from. */ +export function arcPtrEq(l: Arc, r: Arc): boolean { + return arcRoot(l) === arcRoot(r); +} + +function arcRoot(arc: Arc): Arc { + return arc instanceof ArcDyn ? arc.arc : arc; +} + /** * Drop `arc`, whose value has no `[Symbol.dispose]` that drops it: the last one drops it * by `f`, or not at all without one, as a borrow. diff --git a/ts/src/lower/dynamic.rs b/ts/src/lower/dynamic.rs index 489d8e7b1..ce2af5d1f 100644 --- a/ts/src/lower/dynamic.rs +++ b/ts/src/lower/dynamic.rs @@ -3,7 +3,8 @@ //! for its trait (`area$Shape`), and taking the arguments after `self`. That is the //! trait's type, which a TS caller can implement. A coercion to one wraps the value in a //! class of its type's own, whose methods call that type's impl and whose -//! `[Symbol.dispose]`, which a `Box` drops it by, drops the value. +//! `[Symbol.dispose]`, which a `Box` drops it by, drops the value. An +//! `Arc` is an `rt.ArcDyn` around the one a box would be. use rustc_hir::def_id::DefId; use rustc_middle::ty::{self, GenericArgsRef, Instance, Interner as _, Ty, TyCtxt}; diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index 64582314f..a0bea14fc 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -6,7 +6,7 @@ use rustc_index::IndexVec; use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::{self, AggregateKind, BinOp, CastKind, Operand, Place, Rvalue, UnOp}; use rustc_middle::ty::adjustment::PointerCoercion; -use rustc_middle::ty::{self, Instance, Ty}; +use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_span::Span; use super::{Capture, Env, Fx, Slot}; @@ -205,6 +205,10 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let value = self.path(value, "arg", out); self.b.fmt_value(tr, from, value, span, out) } + PointerCoercion::Unsize if let Some((pointee, object)) = arc_object(tcx, from, to) => { + let value = self.operand(op, span, out); + self.arc_object(value, pointee, object, span, out) + } // A future, as the `rt.Future` a `dyn Future` is. PointerCoercion::Unsize if unsized_to(from, to).is_some_and(|part| self.b.t.dyn_future(part).is_some()) => @@ -248,6 +252,30 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } + /// `arc`, an `Arc` of `pointee` unsized to one of the trait object `object`: an + /// `rt.ArcDyn` sharing its count, over what a box of its value unsizes to, or the same + /// `Arc` upcast. + fn arc_object(&mut self, arc: Expr, pointee: Ty<'tcx>, object: Ty<'tcx>, span: Span, out: &mut Vec) -> Expr { + let tcx = self.tcx; + // An upcast is of an `rt.ArcDyn` already, whose object has the supertraits' methods. + let (arc, value) = match pointee.is_trait() { + true => (None, arc), + false => { + let arc = self.path(arc, "arc", out); + (Some(arc.clone()), arc.member("value")) + } + }; + let (from, to) = (Ty::new_box(tcx, pointee), Ty::new_box(tcx, object)); + let value = match self.b.t.dyn_future(object) { + Some(_) => self.b.dyn_future(from, to, value, span), + None => self.b.object_of(value, from, to, span), + }; + match arc { + Some(arc) => Expr::New(Box::new(Expr::Rt("ArcDyn".into())), vec![arc, value]), + None => value, + } + } + /// A discriminant as its number. fn discriminant(&mut self, scrut: Expr, ty: Ty<'tcx>, span: Span, out: &mut Vec) -> Expr { match ty.kind() { @@ -681,6 +709,15 @@ fn unsized_to<'tcx>(from: Ty<'tcx>, to: Ty<'tcx>) -> Option> { } } +/// What an `Arc` unsized to an `Arc` of a trait object points at, and that object. +fn arc_object<'tcx>(tcx: TyCtxt<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> Option<(Ty<'tcx>, Ty<'tcx>)> { + let (ty::Adt(adt, from_args), ty::Adt(_, to_args)) = (from.kind(), to.kind()) else { + return None; + }; + let object = to_args.type_at(0); + (Std::of(tcx, adt.did()) == Some(Std::Arc) && object.is_trait()).then(|| (from_args.type_at(0), object)) +} + /// Whether evaluating `rvalue` can do or throw anything. pub fn effect<'tcx>(rvalue: &Rvalue<'tcx>, fx: &Fx<'_, '_, '_, 'tcx>) -> bool { match rvalue { diff --git a/ts/src/lower/task.rs b/ts/src/lower/task.rs index 2c2f0d494..9dd583743 100644 --- a/ts/src/lower/task.rs +++ b/ts/src/lower/task.rs @@ -153,12 +153,18 @@ pub fn call<'tcx>( ("AsRef", "as_ref") if self_std == Some(Std::Arc) => first(args).member("value"), ("Arc", "downgrade") => Expr::New(Box::new(Expr::Rt("Weak".into())), args), ("Arc", "strong_count") => first(args).member("strong"), + // Two `Arc`s of trait objects are views of the `Arc`s they were made from. + ("Arc", "ptr_eq") if self_ty.is_some_and(Ty::is_trait) => Expr::rt("arcPtrEq", args), ("Arc", "ptr_eq") => { let [l, r] = two(args); l.binary("===", r) } ("Weak", "upgrade") => Expr::rt("weakUpgrade", args), ("Weak", "strong_count") => first(args).member("arc").member("strong"), + ("Weak", "ptr_eq") if self_ty.is_some_and(Ty::is_trait) => { + let [l, r] = two(args); + Expr::rt("arcPtrEq", vec![l.member("arc"), r.member("arc")]) + } ("Weak", "ptr_eq") => { let [l, r] = two(args); l.member("arc").binary("===", r.member("arc")) diff --git a/ts/tests/task.ts b/ts/tests/task.ts index d92a6a474..1cde43b45 100644 --- a/ts/tests/task.ts +++ b/ts/tests/task.ts @@ -50,7 +50,7 @@ export interface Fixture { run(log: Log, id: number, arg: number): void; held(rx: Consumer, guard: Guard): Future; edited(log: Log, id: number, at: number): void; - dyns(log: Log, id: number, at: number): void; + dyns(log: Log, id: number, arg: number): void; cells(log: Log, id: number, at: number): void; }; futures: { @@ -287,7 +287,7 @@ export const steps: [string, (r: Run, arg: number) => void][] = [ if (c !== undefined) r.exec.spawn(r.f.futures.boxed(r.f.Channel.consumer(r.channels[c]), guard(r))); }, ], - ["dyns", (r, arg) => r.f.drops.dyns(r.log, 1000 * r.exec.tasks.length, arg % 6)], + ["dyns", (r, arg) => r.f.drops.dyns(r.log, 1000 * r.exec.tasks.length, arg)], ["cells", (r, arg) => r.f.drops.cells(r.log, 1000 * r.exec.tasks.length, arg)], ]; @@ -373,8 +373,8 @@ export const cases: Uint8Array[] = [ ...Array.from({ length: 253 }, (_, arg) => script(["drops", arg])), // Each of a `Vec`'s edits, its and a tuple's `clone`, and `Ord`'s defaults, panicking at each point or none. ...Array.from({ length: 8 }, (_, at) => script(["edited", at])), - // What boxed trait objects drop, panicking at each point, in a `Drop`, or none. - ...Array.from({ length: 6 }, (_, at) => script(["dyns", at])), + // What boxed and shared trait objects drop, panicking at each point, in a `Drop`, or none. + ...Array.from({ length: 12 }, (_, arg) => script(["dyns", arg])), // What one-time cells drop, for every argument, which picks the scenario. ...Array.from({ length: 256 }, (_, at) => script(["cells", at])), ];