diff --git a/quest/m3/README.md b/quest/m3/README.md index e6424b1eb..2f5429677 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -23,7 +23,6 @@ generic std gap is planned here even when moq never calls it. - [Waiting: type-check in process with tsrs](/quest/m3/ts-tsrs.md) - rust2-ts checks bindings through tsrs instead of `tsc` once it is a stable library - [Drop order in std's folds and iterators](/quest/m3/ts-drop-order.md) - the values that drop still refused in std's consumers, flattens, and collects drop as std's do - [Fresh writes in a body generic over a type](/quest/m3/ts-fresh-type-params.md) - a whole write into fresh memory holding a type parameter's values fills it, as one generic over a length alone does -- [A generic type's bytes at u8](/quest/m3/ts-generic-byte-fields.md) - a `[T; N]`, `Vec`, or `&[T]` field of a generic type is typed as its `u8` instance holds it, or refused - [std's conversions of a reference](/quest/m3/ts-ref-conversions.md) - `to_owned`, `clone_from`, `binary_search`, `size_of_val`, `from_ref`/`from_mut`, and `AsRef`/`Borrow` as a slice translate - [Waiting: a slice object for a mutable part of other values](/quest/m3/ts-slice-object.md) - waits on a moq profile showing the `Proxy` view's traps matter, then decides on an `rt.ByteSlice`-like form - [Port the workflow guard to kixelated/quest](/quest/m3/quest-workflow-guard.md) - quest's environment guard parses YAML as this repository's does @@ -31,6 +30,7 @@ generic std gap is planned here even when moq never calls it. - [Places through an adaptor's argument](/quest/m3/ts-adaptor-places.md) - `iter.zip(&mut v)` of values JS copies lends places as `for x in &mut v` does - [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 +- [Rc and Arc of a slice](/quest/m3/ts-shared-slices.md) - `Rc<[T]>` and `Arc<[T]>` from a `Vec`, a slice, or an iterator translate - [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 diff --git a/quest/m3/ts-generic-byte-fields.md b/quest/m3/ts-generic-byte-fields.md deleted file mode 100644 index 398a34a61..000000000 --- a/quest/m3/ts-generic-byte-fields.md +++ /dev/null @@ -1,22 +0,0 @@ -# [S] A generic type's bytes at u8 - -## Goal - -[rust2-ts](/ts/README.md) types a `[T; N]`, `Vec`, or `&[T]` field of a generic type as -its `u8` instance holds it, or refuses that instance with a span, proven by a differential -test against native Rust of one such type instantiated at `u8` and at another element. - -## Plan - -Found beside [the generic pointer fields](https://github.com/moq-dev/rust2/pull/371): the -definition types each field `T[]`, but an instance at `u8` stores a `Uint8Array`, an -`rt.ByteVec`, or an `rt.ByteSlice`, so `tsc` rejects the instance's code while -translation succeeds. A field whose definition types a pointer as an `rt.Ptr` is -already read as its instance's type through a cast; a union of the element array and -the byte form, cast on read the same way, may fit, as may refusing the `u8` instance as -`generic_erasure` refuses an `Option` of a type parameter that can be `undefined`. - -The `reject` fixture's `mistyped` case tests the output's type check through this gap, -so the fix moves it to another typing gap translation has, if any is left. - -Public API: the translator's output. diff --git a/quest/m3/ts-shared-slices.md b/quest/m3/ts-shared-slices.md new file mode 100644 index 000000000..32c0eae72 --- /dev/null +++ b/quest/m3/ts-shared-slices.md @@ -0,0 +1,17 @@ +# [S] Rc and Arc of a slice + +## Goal + +[rust2-ts](/ts/README.md) translates an `Rc<[T]>` and an `Arc<[T]>` made from a `Vec`, a +slice, or an iterator, read as the slice, cloned, and dropped, proven by a differential +test against native Rust at `u8`, at another element, and at one that drops. + +## Plan + +Found writing [a generic type's byte fields](https://github.com/moq-dev/rust2/pull/375)' +fixture: `Rc::from(vec)` and `Rc::from(slice)` are refused as unsupported calls to +`From`. A shared slice is what a generic type's `[T]` already is, so the form of a +`u8` instance is the open question: an `rt.ByteSlice` as a `Box<[u8]>` is, or one that +counts its owners as `rt.Arc` does. + +Public API: the translator's output. diff --git a/ts/MIGRATE.md b/ts/MIGRATE.md index 53c0f3e15..bef7da922 100644 --- a/ts/MIGRATE.md +++ b/ts/MIGRATE.md @@ -53,6 +53,11 @@ the form of, such as `*mut T`, `NonNull`, or `&'a mut T`, is an `rt.Ptr`, the object, an `rt.Place`, or an `rt.ByteSlice`, rather than `rt.Place` or `T`: a caller reading one casts it to what its instance holds, as the output does. +- A generic type's field holding a run of a type parameter is an `rt.ArrayOf` for + `[T; N]`, an `rt.SliceOf` for `[T]` behind a reference or a `Box`, an `rt.VecOf` + for `Vec`, or an `rt.CowOf` for `Cow<[T]>`, rather than `T[]` or `rt.Cow`: + each also holds the byte form of its `u8` instance, which a caller reading one casts + it to, as the output does. - A closure, a `fn` pointer, a `dyn Fn`, or a function item as a value returns `undefined` for `()`, not `void`, as in `(a0: rt.u8) => undefined`: a caller passes such a parameter a function typed `=> undefined`. diff --git a/ts/README.md b/ts/README.md index a223eb75b..8fe754d1f 100644 --- a/ts/README.md +++ b/ts/README.md @@ -333,7 +333,10 @@ type is one instance's, declaring the instance it takes as `self`: `fmt$fmt_Debug_fmt_Pair(self: Wrap, f: rt.Formatter)`. A reference or pointer in a generic type to what only an instance decides the form of, such as `*mut T` or `&'a mut T`, is an `rt.Ptr`: the object, an `rt.Place`, or an `rt.ByteSlice`, -which each read of an instance's field casts to what it holds. A type's module exports the +which each read of an instance's field casts to what it holds. So is a run of a +parameter, whose `u8` instance holds bytes: `[T; N]` is an `rt.ArrayOf`, a `T[]` or a +`Uint8Array`, and `[T]`, `Vec`, and `Cow<[T]>` an `rt.SliceOf`, an `rt.VecOf`, +and an `rt.CowOf`. A type's module exports the type by its own name, which a caller writes `Decoder.Decoder`, and a function whose name and exports it as its own: `function new_` is `Decoder.new`. A module imports a function or value by its name, and a type's module whole by the type's, `import * as Decoder`, @@ -846,7 +849,9 @@ built natively for wasm32 and run beside its translation on the same inputs by `NonZero`, and raw pointers: a linked list of boxed nodes as `hashlink` keeps one, through a union and a `MaybeUninit` entry, pointers to locals, fields, and whole structs, those `UnsafeCell::get` gives, as crossbeam-epoch's own `OnceLock` keeps its collector, and - those a generic type holds to its parameter, at each form a pointer takes. Its + those a generic type holds to its parameter, at each form a pointer takes, and a + generic type's arrays, slices, `Vec`s, and `Cow`s of its parameter at bytes, at + `u16`, and at values that drop. Its differential test runs through `caller.ts`, a hand-written caller that also prints a `printable` error nothing translated prints, and adds every 64- and 128-bit case over each pair of values next to a power of two, @@ -889,8 +894,7 @@ built natively for wasm32 and run beside its translation on the same inputs by from either end, and its `shared` feature adds a module of the dependency's name, with the errors in `refused.txt`, `rev.txt`, and `shared.txt`. - `reject` holds constructs outside the subset; its expected errors are `expected.txt`, - and its expected census is `census.md`. `mistyped.toml` translates a typing gap that - `tsc` rejects, with the errors in `mistyped.txt`. + and its expected census is `census.md`. `tests/spawn.ts` checks that `rt.spawn` yields to a timer after its 128-poll budget, and rejects when a future panics as it drops. `tests/retain.ts` runs a collection's `retain` diff --git a/ts/fixtures/lang/expected/core/bool.ts b/ts/fixtures/lang/expected/core/bool.ts index 7660e9693..daa6d4fd5 100644 --- a/ts/fixtures/lang/expected/core/bool.ts +++ b/ts/fixtures/lang/expected/core/bool.ts @@ -140,6 +140,13 @@ export function then$0afp4no(self: boolean, f: () => rt.Result rt.u16[]): rt.u16[] | undefined { + if (!self) { + return undefined; + } + return []; +} + export function then$1i9qaz4(self: boolean, _: () => rt.ByteVec): rt.ByteVec | undefined { if (!self) { return undefined; diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts index 7807d409e..edbec8dbe 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -25,6 +25,7 @@ import type * as cycles_Logged from "../cycles.Logged.ts"; import * as defaults_Made from "../defaults.Made.ts"; import type * as dyns_Shape from "../dyns.Shape.ts"; import * as edits_Named from "../edits.Named.ts"; +import type * as Ticked from "../generics.Ticked.ts"; import type * as hints_Unit from "../hints.Unit.ts"; import type * as Badge from "../iters.Badge.ts"; import type * as Quarter from "../iters.Quarter.ts"; @@ -248,6 +249,13 @@ export function unwrapOrDefault$0k1p6nh(self: [rt.u64 | undefined, defaults_Made return self; } +export function unwrapOrDefault$001fvl5(self: rt.u16 | undefined): rt.u16 { + if (self === undefined) { + return 0; + } + return self; +} + export function unwrapOrDefault$1q0ps0j(self: rt.u8 | undefined): rt.u8 { if (self === undefined) { return 0; @@ -621,6 +629,13 @@ export function map$0rbsrz6(self: rt.u8 | undefined, f: (a0: rt.u8) => rt.u8 | u return f(self); } +export function map$12l9avg(self: rt.u8 | undefined, f: (a0: rt.u8) => Ticked.Ticked[]): Ticked.Ticked[] | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + export function map$1qp1ym6(self: rt.u8 | undefined, f: (a0: rt.u8) => rt.u32): rt.u32 | undefined { if (self === undefined) { return undefined; @@ -1856,6 +1871,20 @@ export function clone$14nprly(self: string | undefined): string | undefined { return self; } +export function clone$096c3ul(self: rt.u16[] | undefined): rt.u16[] | undefined { + if (self === undefined) { + return undefined; + } + return self.slice(); +} + +export function clone$1grnave(self: rt.ByteVec | undefined): rt.ByteVec | undefined { + if (self === undefined) { + return undefined; + } + return rt.byteVecFrom(rt.byteVecView(self)); +} + export function clone$0vcwlo5(self: edits_Named.Named | undefined): edits_Named.Named | undefined { if (self === undefined) { return undefined; diff --git a/ts/fixtures/lang/expected/generics.Fixed.ts b/ts/fixtures/lang/expected/generics.Fixed.ts new file mode 100644 index 000000000..294d05b45 --- /dev/null +++ b/ts/fixtures/lang/expected/generics.Fixed.ts @@ -0,0 +1,36 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +export function fmt$fmt_Debug_u16(self: Fixed, f: rt.Formatter): rt.Result { + const arg = self.pair as rt.u16[]; + const _3: string = "Fixed"; + const _4: string = "pair"; + const _5: rt.Fmt = (f: rt.Formatter) => rt.fmtList(arg, f, rt.u16Debug); + const _7: string = "tag"; + const _8: rt.Fmt = (f: rt.Formatter) => rt.u8Debug(self.tag, f); + return rt.debugStructFinish(rt.debugStructField(rt.debugStructField(rt.fmtDebugStruct(f, _3), _4, _5), _7, _8)); +} + +export function fmt$fmt_Debug_u8(self: Fixed, f: rt.Formatter): rt.Result { + const _3: string = "Fixed"; + const _4: string = "pair"; + const _6: rt.ByteSlice = rt.byteSliceFrom(self.pair as Uint8Array); + const _5: rt.Fmt = (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(_6), f, rt.u8Debug); + const _7: string = "tag"; + const _8: rt.Fmt = (f: rt.Formatter) => rt.u8Debug(self.tag, f); + return rt.debugStructFinish(rt.debugStructField(rt.debugStructField(rt.fmtDebugStruct(f, _3), _4, _5), _7, _8)); +} + +/** A generic type JS copies, holding an array of its parameter. */ +export class Fixed { + pair: rt.ArrayOf; + tag: rt.u8; + + constructor(pair: rt.ArrayOf, tag: rt.u8) { + this.pair = pair; + this.tag = tag; + } +} + +//# sourceMappingURL=generics.Fixed.ts.map diff --git a/ts/fixtures/lang/expected/generics.Lends.ts b/ts/fixtures/lang/expected/generics.Lends.ts new file mode 100644 index 000000000..1f50478ae --- /dev/null +++ b/ts/fixtures/lang/expected/generics.Lends.ts @@ -0,0 +1,14 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** + * A generic type lending a run of its parameter, which it writes through, and a function + * of one. + */ +export interface Lends { + run: rt.SliceOf; + last: (a0: rt.SliceOf) => rt.Ptr | undefined; +} + +//# sourceMappingURL=generics.Lends.ts.map diff --git a/ts/fixtures/lang/expected/generics.Run.ts b/ts/fixtures/lang/expected/generics.Run.ts new file mode 100644 index 000000000..4a14a8ec5 --- /dev/null +++ b/ts/fixtures/lang/expected/generics.Run.ts @@ -0,0 +1,66 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +export function fmt$fmt_Debug_u16(self: Run, f: rt.Formatter): rt.Result { + if (self.tag === "Listed") { + const arg2 = self._0 as rt.u16[]; + const _5: string = "Listed"; + const _6: rt.Fmt = (f: rt.Formatter) => rt.fmtList(arg2, f, rt.u16Debug); + return rt.debugTupleFinish(rt.debugTupleField(rt.fmtDebugTuple(f, _5), _6)); + } + if (self.tag === "Fixed") { + const arg = self.array as rt.u16[]; + const _9: string = "Fixed"; + const _10: string = "array"; + const _11: rt.Fmt = (f: rt.Formatter) => rt.fmtList(arg, f, rt.u16Debug); + return rt.debugStructFinish(rt.debugStructField(rt.fmtDebugStruct(f, _9), _10, _11)); + } + return rt.fmtWriteStr(f, "Empty"); +} + +export function fmt$fmt_Debug_u8(self: Run, f: rt.Formatter): rt.Result { + if (self.tag === "Listed") { + const arg = self._0 as rt.ByteVec; + const _5: string = "Listed"; + const _6: rt.Fmt = (f: rt.Formatter) => rt.fmtList(rt.byteVecView(arg), f, rt.u8Debug); + return rt.debugTupleFinish(rt.debugTupleField(rt.fmtDebugTuple(f, _5), _6)); + } + if (self.tag === "Fixed") { + const __self0: rt.ByteSlice = rt.byteSliceFrom(self.array as Uint8Array); + const _9: string = "Fixed"; + const _10: string = "array"; + const _11: rt.Fmt = (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(__self0), f, rt.u8Debug); + return rt.debugStructFinish(rt.debugStructField(rt.fmtDebugStruct(f, _9), _10, _11)); + } + return rt.fmtWriteStr(f, "Empty"); +} + +/** An enum holding a run of its parameter in a variant. */ +export type Run = + | { tag: "Listed"; _0: rt.VecOf } + | { tag: "Fixed"; array: rt.ArrayOf } + | { tag: "Empty" }; + +export function first$u16(self: Run): rt.u16 | undefined { + if (self.tag === "Listed") { + return rt.sliceFirst(self._0 as rt.u16[]); + } + if (self.tag === "Fixed") { + return (self.array as rt.u16[])[0]; + } + return undefined; +} + +export function first$u8(self: Run): rt.u8 | undefined { + if (self.tag === "Listed") { + return rt.byteSliceFirst(rt.byteVecSlice(self._0 as rt.ByteVec)); + } + if (self.tag === "Fixed") { + const array: rt.ByteSlice = rt.byteSliceFrom(self.array as Uint8Array); + return array.data[array.start]; + } + return undefined; +} + +//# sourceMappingURL=generics.Run.ts.map diff --git a/ts/fixtures/lang/expected/generics.Runs.ts b/ts/fixtures/lang/expected/generics.Runs.ts new file mode 100644 index 000000000..f9b772f86 --- /dev/null +++ b/ts/fixtures/lang/expected/generics.Runs.ts @@ -0,0 +1,183 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { copy$array_u16, copy$array_u8 } from "./lib.ts"; +import { clone$096c3ul as option_clone$096c3ul, clone$1grnave as option_clone$1grnave } from "./core/option.ts"; +import type * as generics_Run from "./generics.Run.ts"; + +export function clone$Clone_u16(self: Runs): Runs { + return new Runs(copy$array_u16(copy$array_u16(self.array as rt.u16[])), (self.list as rt.u16[]).slice(), self.view as rt.u16[], (self.boxed as rt.u16[]).slice(), rt.cowClone(self.cow as rt.Cow), (self.pairs as rt.u16[][]).map(copy$array_u16), option_clone$096c3ul(self.maybe as rt.u16[] | undefined)); +} + +export function clone$Clone_u8(self: Runs): Runs { + return new Runs(copy$array_u8(rt.byteSliceToArray(rt.byteSliceFrom(self.array as Uint8Array))), rt.byteVecFrom(rt.byteVecView(self.list as rt.ByteVec)), self.view as rt.ByteSlice, rt.byteSliceFrom(rt.byteSliceToArray(self.boxed as rt.ByteSlice)), rt.byteCowClone(self.cow as rt.ByteCow), (self.pairs as Uint8Array[]).map(copy$array_u8), option_clone$1grnave(self.maybe as rt.ByteVec | undefined)); +} + +export function fmt$fmt_Debug_u16(self: Runs, f: rt.Formatter): rt.Result { + const arg = self.array as rt.u16[]; + const _7: rt.Fmt = (f: rt.Formatter) => rt.fmtList(arg, f, rt.u16Debug); + const arg2 = self.list as rt.u16[]; + const _9: rt.Fmt = (f: rt.Formatter) => rt.fmtList(arg2, f, rt.u16Debug); + const arg3 = self.view as rt.u16[]; + const _11: rt.Fmt = (f: rt.Formatter) => rt.fmtList(arg3, f, rt.u16Debug); + const arg4 = self.boxed as rt.u16[]; + const _13: rt.Fmt = (f: rt.Formatter) => rt.fmtList(arg4, f, rt.u16Debug); + const arg5 = self.cow as rt.Cow; + const _15: rt.Fmt = (f: rt.Formatter) => rt.fmtList(rt.cowSlice(arg5), f, rt.u16Debug); + const arg6 = self.pairs as rt.u16[][]; + const _17: rt.Fmt = (f: rt.Formatter) => rt.fmtList(arg6, f, (value: rt.u16[], f: rt.Formatter) => rt.fmtList(value, f, rt.u16Debug)); + const arg7 = self.maybe as rt.u16[] | undefined; + const names: string[] = ["array", "list", "view", "boxed", "cow", "pairs", "maybe"]; + const values: rt.Fmt[] = [_7, _9, _11, _13, _15, _17, (f: rt.Formatter) => rt.fmtOption(arg7, f, (value: rt.u16[], f: rt.Formatter) => rt.fmtList(value, f, rt.u16Debug))]; + return rt.fmtDebugStructFields(f, "Runs", names, values); +} + +export function fmt$fmt_Debug_u8(self: Runs, f: rt.Formatter): rt.Result { + const names: string[] = ["array", "list", "view", "boxed", "cow", "pairs", "maybe"]; + const _8: rt.ByteSlice = rt.byteSliceFrom(self.array as Uint8Array); + const arg = self.list as rt.ByteVec; + const _9: rt.Fmt = (f: rt.Formatter) => rt.fmtList(rt.byteVecView(arg), f, rt.u8Debug); + const arg2 = self.view as rt.ByteSlice; + const _11: rt.Fmt = (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(arg2), f, rt.u8Debug); + const arg3 = self.boxed as rt.ByteSlice; + const _13: rt.Fmt = (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(arg3), f, rt.u8Debug); + const arg4 = self.cow as rt.ByteCow; + const _15: rt.Fmt = (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(rt.byteCowSlice(arg4)), f, rt.u8Debug); + const arg5 = self.pairs as Uint8Array[]; + const _17: rt.Fmt = (f: rt.Formatter) => rt.fmtList(arg5, f, (value: Uint8Array, f: rt.Formatter) => rt.fmtList(value, f, rt.u8Debug)); + const arg6 = self.maybe as rt.ByteVec | undefined; + const values: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(_8), f, rt.u8Debug), _9, _11, _13, _15, _17, (f: rt.Formatter) => rt.fmtOption(arg6, f, (value: rt.ByteVec, f: rt.Formatter) => rt.fmtList(rt.byteVecView(value), f, rt.u8Debug))]; + return rt.fmtDebugStructFields(f, "Runs", names, values); +} + +export function eq$cmp_PartialEq_u16(self: Runs, other: Runs): boolean { + if (rt.eqSlice(rt.same)(self.array as rt.u16[], other.array as rt.u16[])) { + if (rt.eqSlice(rt.same)(self.list as rt.u16[], other.list as rt.u16[])) { + if (rt.eqSlice(rt.same)(self.view as rt.u16[], other.view as rt.u16[])) { + if (rt.eqSlice(rt.same)(self.boxed as rt.u16[], other.boxed as rt.u16[])) { + if (rt.eqSlice(rt.same)(rt.cowSlice(self.cow as rt.Cow), rt.cowSlice(other.cow as rt.Cow))) { + if (rt.eqSlice(rt.eqSlice(rt.same))(self.pairs as rt.u16[][], other.pairs as rt.u16[][])) { + return rt.eqOption(rt.eqSlice(rt.same))(self.maybe as rt.u16[] | undefined, other.maybe as rt.u16[] | undefined); + } + } + } + } + } + } + return false; +} + +export function eq$cmp_PartialEq_u8(self: Runs, other: Runs): boolean { + if (rt.eqBytes(rt.byteSliceFrom(self.array as Uint8Array), rt.byteSliceFrom(other.array as Uint8Array))) { + if (rt.eqBytes(self.list as rt.ByteVec, other.list as rt.ByteVec)) { + if (rt.byteSliceEq(self.view as rt.ByteSlice, other.view as rt.ByteSlice)) { + if (rt.eqBytes(self.boxed as rt.ByteSlice, other.boxed as rt.ByteSlice)) { + if (rt.eqBytes(self.cow as rt.ByteCow, other.cow as rt.ByteCow)) { + if (rt.eqSlice(rt.eqBytes)(self.pairs as Uint8Array[], other.pairs as Uint8Array[])) { + return rt.eqOption(rt.eqBytes)(self.maybe as rt.ByteVec | undefined, other.maybe as rt.ByteVec | undefined); + } + } + } + } + } + } + return false; +} + +/** + * A generic type holding runs of its parameter in each form JS keeps a run of bytes + * apart in, which only an instance decides. + */ +export class Runs { + array: rt.ArrayOf; + list: rt.VecOf; + view: rt.SliceOf; + boxed: rt.SliceOf; + cow: rt.CowOf; + pairs: rt.ArrayOf[]; + maybe: rt.VecOf | undefined; + + constructor(array: rt.ArrayOf, list: rt.VecOf, view: rt.SliceOf, boxed: rt.SliceOf, cow: rt.CowOf, pairs: rt.ArrayOf[], maybe: rt.VecOf | undefined) { + this.array = array; + this.list = list; + this.view = view; + this.boxed = boxed; + this.cow = cow; + this.pairs = pairs; + this.maybe = maybe; + } + + [Symbol.dispose](): void { + rt.dropAll(this.array as T[]); + rt.dropAll(this.list as T[]); + rt.dropAll(this.boxed as T[]); + rt.cowDrop(this.cow as rt.Cow); + rt.dropAll(this.pairs as T[][], (value: T[]) => rt.dropAll(value)); + rt.dropAll(this.maybe as T[] | undefined); + } +} + +export function total$u16(self: Runs): rt.usize { + return rt.usizeAdd(rt.usizeAdd(rt.usizeAdd(rt.usizeAdd(rt.usizeAdd((self.array as rt.u16[]).length, (self.list as rt.u16[]).length), (self.view as rt.u16[]).length), (self.boxed as rt.u16[]).length), rt.cowSlice(self.cow as rt.Cow).length), (self.pairs as rt.u16[][]).length); +} + +export function total$u8(self: Runs): rt.usize { + return rt.usizeAdd(rt.usizeAdd(rt.usizeAdd(rt.usizeAdd(rt.usizeAdd(rt.byteSliceFrom(self.array as Uint8Array).length, (self.list as rt.ByteVec).length), (self.view as rt.ByteSlice).length), (self.boxed as rt.ByteSlice).length), rt.byteCowSlice(self.cow as rt.ByteCow).length), (self.pairs as Uint8Array[]).length); +} + +export function push$u16(self: Runs, item: rt.u16): void { + (self.list as rt.u16[]).push(item); + const owned = rt.cowIntoOwned(self.cow as rt.Cow); + (self.cow as rt.Cow) = owned; + owned.push(item); + (self.pairs as rt.u16[][]).push(Array.from({ length: 2 }, (): rt.u16 => { + return item; + })); + rt.sliceRotateLeft(self.array as rt.u16[], 1); + (self.array as rt.u16[])[2] = item; + rt.idx(self.boxed as rt.u16[], 0); + (self.boxed as rt.u16[])[0] = item; + if ((self.maybe as rt.u16[] | undefined) !== undefined) { + ((self.maybe as rt.u16[] | undefined) as rt.u16[]).push(item); + } +} + +export function push$u8(self: Runs, item: rt.u8): void { + rt.byteVecPush(self.list as rt.ByteVec, item); + const owned = rt.byteCowIntoOwned(self.cow as rt.ByteCow); + (self.cow as rt.ByteCow) = owned; + rt.byteVecPush(owned, item); + (self.pairs as Uint8Array[]).push(rt.bytes(2).fill(item)); + rt.byteSliceRotateLeft(rt.byteSliceFrom(self.array as Uint8Array), 1); + (self.array as Uint8Array)[2] = item; + rt.idx(self.boxed as rt.ByteSlice, 0); + const _24: rt.ByteSlice = self.boxed as rt.ByteSlice; + _24.data[_24.start] = item; + if ((self.maybe as rt.ByteVec | undefined) !== undefined) { + rt.byteVecPush((self.maybe as rt.ByteVec | undefined) as rt.ByteVec, item); + } +} + +export function run$u16(self: Runs): generics_Run.Run { + const _2: rt.usize = rt.usizeRem((self.list as rt.u16[]).length, 3); + if (_2 === 0) { + return { tag: "Listed", _0: (self.list as rt.u16[]).slice() } as generics_Run.Run; + } + if (_2 === 1) { + return { tag: "Fixed", array: [(self.array as rt.u16[])[0], (self.array as rt.u16[])[2]] } as generics_Run.Run; + } + return { tag: "Empty" } as generics_Run.Run; +} + +export function run$u8(self: Runs): generics_Run.Run { + const _2: rt.usize = rt.usizeRem((self.list as rt.ByteVec).length, 3); + if (_2 === 0) { + return { tag: "Listed", _0: rt.byteVecFrom(rt.byteVecView(self.list as rt.ByteVec)) } as generics_Run.Run; + } + if (_2 === 1) { + return { tag: "Fixed", array: Uint8Array.of((self.array as Uint8Array)[0], (self.array as Uint8Array)[2]) } as generics_Run.Run; + } + return { tag: "Empty" } as generics_Run.Run; +} + +//# sourceMappingURL=generics.Runs.ts.map diff --git a/ts/fixtures/lang/expected/generics.Ticked.ts b/ts/fixtures/lang/expected/generics.Ticked.ts new file mode 100644 index 000000000..1154330fe --- /dev/null +++ b/ts/fixtures/lang/expected/generics.Ticked.ts @@ -0,0 +1,34 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** Logs its id as it drops, and as it is cloned, the id with the high bit set. */ +export class Ticked { + id: rt.u8; + log: rt.Arc>; + + constructor(id: rt.u8, log: rt.Arc>) { + this.id = id; + this.log = log; + } + + [Symbol.dispose](): void { + drop$ops_Drop(this); + this.log[Symbol.dispose](); + } +} + +export function clone$Clone(self: Ticked): Ticked { + const _5: rt.RefCell = rt.refCellBorrowMut(self.log.value); + rt.byteVecPush(_5.value, 128 | self.id); + rt.refMutRelease(_5); + return new Ticked(self.id, rt.arcClone(self.log)); +} + +export function drop$ops_Drop(self: Ticked): void { + const _5: rt.RefCell = rt.refCellBorrowMut(self.log.value); + rt.byteVecPush(_5.value, self.id); + rt.refMutRelease(_5); +} + +//# sourceMappingURL=generics.Ticked.ts.map diff --git a/ts/fixtures/lang/expected/generics.ts b/ts/fixtures/lang/expected/generics.ts index 92cdcd688..40218e409 100644 --- a/ts/fixtures/lang/expected/generics.ts +++ b/ts/fixtures/lang/expected/generics.ts @@ -1,12 +1,18 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$array_generics_Either_u8_shapes_Point, copy$generics_Wrap_shapes_Point, copy$generics_Wrap_u8, copy$shapes_Gauge } from "./lib.ts"; -import { unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr } from "./core/option.ts"; +import { copy$array_generics_Either_u8_shapes_Point, copy$generics_Fixed_u16, copy$generics_Fixed_u8, copy$generics_Wrap_shapes_Point, copy$generics_Wrap_u8, copy$shapes_Gauge, drop$generics_Run_generics_Ticked } from "./lib.ts"; +import { then$0h950d8, then$1i9qaz4 } from "./core/bool.ts"; +import { unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOrDefault$001fvl5 as option_unwrapOrDefault$001fvl5, unwrapOrDefault$1q0ps0j as option_unwrapOrDefault$1q0ps0j, map$12l9avg as option_map$12l9avg } from "./core/option.ts"; import { put as fmt_put } from "./fmt.ts"; import type * as fmt_Pair from "./fmt.Pair.ts"; import * as Either from "./generics.Either.ts"; +import * as Fixed from "./generics.Fixed.ts"; +import type * as Lends from "./generics.Lends.ts"; +import * as generics_Run from "./generics.Run.ts"; +import * as Runs from "./generics.Runs.ts"; import * as generics_Tagged from "./generics.Tagged.ts"; +import * as Ticked from "./generics.Ticked.ts"; import * as Wrap from "./generics.Wrap.ts"; import * as shapes_Gauge from "./shapes.Gauge.ts"; import type * as Meters from "./shapes.Meters.ts"; @@ -101,4 +107,184 @@ export function reset$shapes_Gauge(xs: shapes_Gauge.Gauge[]): void { } } +/** `fixed` with its pair swapped, in a copy of it. */ +export function swapped$u16(fixed: Fixed.Fixed): Fixed.Fixed { + const copy: Fixed.Fixed = copy$generics_Fixed_u16(fixed); + rt.sliceSwap(copy.pair as rt.u16[], 0, 1); + return copy$generics_Fixed_u16(copy); +} + +/** `fixed` with its pair swapped, in a copy of it. */ +export function swapped$u8(fixed: Fixed.Fixed): Fixed.Fixed { + const copy: Fixed.Fixed = copy$generics_Fixed_u8(fixed); + rt.byteSliceSwap(rt.byteSliceFrom(copy.pair as Uint8Array), 0, 1); + return copy$generics_Fixed_u8(copy); +} + +/** Writes `item` over each element of `run`, through a `&mut` to a field. */ +export function fill$u16(run: rt.u16[], item: rt.u16): void { + const iter: rt.Iter> = rt.iterSliceMut(run); + while (true) { + const _5: rt.Place | rt.Done = iter.next(); + if (_5 === rt.DONE) { + break; + } + _5.v = item; + } +} + +/** Writes `item` over each element of `run`, through a `&mut` to a field. */ +export function fill$u8(run: rt.ByteSlice, item: rt.u8): void { + const iter: rt.Iter> = rt.iterSliceMut(rt.byteSliceView(run)); + while (true) { + const _5: rt.Place | rt.Done = iter.next(); + if (_5 === rt.DONE) { + break; + } + _5.v = item; + } +} + +/** + * [`Runs`], [`Run`], and [`Fixed`] at `u8`, whose runs JS keeps as bytes, and at + * `u16`, then [`Runs`] and [`Run`] of values that drop, in the order of their fields. + */ +export function runs(data: rt.ByteSlice, out: rt.ByteVec): void { + let _266!: rt.Cow; + let run3!: generics_Run.Run; + const data2: rt.ByteVec = rt.iterToByteVec(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_2: rt.u8): rt.u8 => { + return _2; + }), undefined, true); + const n: rt.u8 = option_unwrapOrDefault$1q0ps0j(rt.byteSliceFirst(rt.byteVecSlice(data2))); + const _13: rt.ByteVec = rt.byteVecFrom(rt.byteVecView(data2)); + const _15: rt.ByteSlice = rt.byteVecSlice(data2); + const _17: rt.ByteSlice = rt.byteVecSlice(rt.byteVecFrom(rt.byteVecView(data2))); + const _20: rt.ByteCow = rt.byteVecSlice(data2); + const _23: Uint8Array[] = []; + const runs: Runs.Runs = new Runs.Runs(rt.bytes(3).fill(n), _13, _15, _17, _20, _23, then$1i9qaz4(rt.usizeRem(data2.length, 2) === 0, (): rt.ByteVec => { + return new rt.ByteVec(); + })); + const before: Runs.Runs = Runs.clone$Clone_u8(runs); + const iter: rt.Iter = rt.iterTake(rt.iterSlice(rt.byteSliceView(rt.byteVecSlice(data2))), 3); + while (true) { + const _38: rt.u8 | rt.Done = iter.next(); + if (_38 === rt.DONE) { + break; + } + Runs.push$u8(runs, _38); + } + const _44: rt.ByteSlice | undefined = rt.optionMap(rt.sliceFirst(runs.pairs as Uint8Array[]), rt.byteSliceFrom); + if (_44 !== undefined) { + fill$u8(_44, n); + } + fill$u8(rt.byteSliceRange(rt.byteSliceFrom(runs.array as Uint8Array), 1), 7); + const taken3 = runs.list as rt.ByteVec; + (runs.list as rt.ByteVec) = new rt.ByteVec(); + const taken: rt.ByteVec = taken3; + const _59: rt.ByteSlice = rt.byteVecSlice(taken); + const lent: Lends.Lends = { run: _59, last: ((a0: rt.ByteSlice): rt.u8 | undefined => { + return rt.byteSliceLast(a0); + }) as (a0: rt.SliceOf) => rt.Ptr | undefined }; + const last: rt.u8 | undefined = (lent.last as (a0: rt.ByteSlice) => rt.u8 | undefined)(runs.view as rt.ByteSlice); + const _65: rt.Place | undefined = rt.sliceLastMut(rt.byteSliceView(_59)); + if (_65 !== undefined) { + _65.v = n; + } + fill$u8(_59, 3); + const run: generics_Run.Run = Runs.run$u8(runs); + const fixed: Fixed.Fixed = new Fixed.Fixed(Uint8Array.of(n, n), 1); + const copy: Fixed.Fixed = copy$generics_Fixed_u8(fixed); + (copy.pair as Uint8Array)[0] = 9; + const swapped: Fixed.Fixed = swapped$u8(copy$generics_Fixed_u8(copy)); + const _88: rt.usize = Runs.total$u8(runs); + const _91: boolean = Runs.eq$cmp_PartialEq_u8(runs, before); + const _95: rt.u8 | undefined = generics_Run.first$u8(run); + const args2: rt.Fmt[] = [(f: rt.Formatter) => Runs.fmt$fmt_Debug_u8(runs, f), (f: rt.Formatter) => Runs.fmt$fmt_Debug_u8(before, f), (f: rt.Formatter) => rt.fmtList(rt.byteVecView(taken), f, rt.u8Debug), (f: rt.Formatter) => generics_Run.fmt$fmt_Debug_u8(run, f), (f: rt.Formatter) => Fixed.fmt$fmt_Debug_u8(fixed, f), (f: rt.Formatter) => Fixed.fmt$fmt_Debug_u8(copy, f), (f: rt.Formatter) => Fixed.fmt$fmt_Debug_u8(swapped, f), (f: rt.Formatter) => rt.usizeDisplay(_88, f), (f: rt.Formatter) => rt.fmtBool(_91, f), (f: rt.Formatter) => rt.fmtOption(_95, f, rt.u8Debug), (f: rt.Formatter) => rt.fmtOption(last, f, rt.u8Debug)]; + fmt_put(out, rt.fmtFormat([args2[0], " ", args2[1], " ", args2[2], " ", args2[3], " ", args2[4], " ", args2[5], " ", args2[6], " ", args2[7], " ", args2[8], " ", args2[9], " ", args2[10]])); + const data3: rt.u16[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_22: rt.u8): rt.u16 => { + return _22 as rt.u16; + }), undefined, 2, true); + const n2: rt.u16 = option_unwrapOrDefault$001fvl5(rt.sliceFirst(data3)); + const _129: rt.u16[] = data3.slice(); + const _131: rt.u16[] = data3; + const _133: rt.u16[] = data3.slice(); + const _136: rt.Cow = new rt.Borrowed(data3); + const _139: rt.u16[][] = []; + const runs2: Runs.Runs = new Runs.Runs(Array.from({ length: 3 }, (): rt.u16 => { + return n2; + }), _129, _131, _133, _136, _139, then$0h950d8(rt.usizeRem(data3.length, 2) === 0, (): rt.u16[] => { + return []; + })); + const before2: Runs.Runs = Runs.clone$Clone_u16(runs2); + const iter2: rt.Iter = rt.iterTake(rt.iterSlice(data3), 3); + while (true) { + const _154: rt.u16 | rt.Done = iter2.next(); + if (_154 === rt.DONE) { + break; + } + Runs.push$u16(runs2, _154); + } + const _160: rt.u16[] | undefined = rt.sliceFirst(runs2.pairs as rt.u16[][]); + if (_160 !== undefined) { + fill$u16(_160, n2); + } + fill$u16(rt.sliceRangeMut(runs2.array as rt.u16[], 1), 7 as rt.u16); + const taken4 = runs2.list as rt.u16[]; + (runs2.list as rt.u16[]) = []; + const taken2: rt.u16[] = taken4; + const _175: rt.u16[] = taken2; + const lent2: Lends.Lends = { run: _175, last: ((a02: rt.u16[]): rt.u16 | undefined => { + return rt.sliceLast(a02); + }) as (a0: rt.SliceOf) => rt.Ptr | undefined }; + const last2: rt.u16 | undefined = (lent2.last as (a0: rt.u16[]) => rt.u16 | undefined)(runs2.view as rt.u16[]); + const _181: rt.Place | undefined = rt.sliceLastMut(_175); + if (_181 !== undefined) { + _181.v = n2; + } + fill$u16(_175, 3 as rt.u16); + const run2: generics_Run.Run = Runs.run$u16(runs2); + const fixed2: Fixed.Fixed = new Fixed.Fixed([n2, n2], 1); + const copy2: Fixed.Fixed = copy$generics_Fixed_u16(fixed2); + (copy2.pair as rt.u16[])[0] = 9 as rt.u16; + const swapped2: Fixed.Fixed = swapped$u16(copy$generics_Fixed_u16(copy2)); + const _204: rt.usize = Runs.total$u16(runs2); + const _207: boolean = Runs.eq$cmp_PartialEq_u16(runs2, before2); + const _211: rt.u16 | undefined = generics_Run.first$u16(run2); + const args4: rt.Fmt[] = [(f: rt.Formatter) => Runs.fmt$fmt_Debug_u16(runs2, f), (f: rt.Formatter) => Runs.fmt$fmt_Debug_u16(before2, f), (f: rt.Formatter) => rt.fmtList(taken2, f, rt.u16Debug), (f: rt.Formatter) => generics_Run.fmt$fmt_Debug_u16(run2, f), (f: rt.Formatter) => Fixed.fmt$fmt_Debug_u16(fixed2, f), (f: rt.Formatter) => Fixed.fmt$fmt_Debug_u16(copy2, f), (f: rt.Formatter) => Fixed.fmt$fmt_Debug_u16(swapped2, f), (f: rt.Formatter) => rt.usizeDisplay(_204, f), (f: rt.Formatter) => rt.fmtBool(_207, f), (f: rt.Formatter) => rt.fmtOption(_211, f, rt.u16Debug), (f: rt.Formatter) => rt.fmtOption(last2, f, rt.u16Debug)]; + fmt_put(out, rt.fmtFormat([args4[0], " ", args4[1], " ", args4[2], " ", args4[3], " ", args4[4], " ", args4[5], " ", args4[6], " ", args4[7], " ", args4[8], " ", args4[9], " ", args4[10]])); + const log: rt.Arc> = new rt.Arc(new rt.RefCell(new rt.ByteVec())); + const tick: (a0: rt.u8) => Ticked.Ticked = (id: rt.u8): Ticked.Ticked => { + return new Ticked.Ticked(id, rt.arcClone(log)); + }; + const ticks: Ticked.Ticked[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_28: rt.u8): Ticked.Ticked => { + return tick(_28); + }), undefined, 8, true); + const _246: Ticked.Ticked[] = [tick(1), tick(2), tick(3)]; + const _256: Ticked.Ticked[] = ticks.map(Ticked.clone$Clone); + const _258: Ticked.Ticked[] = ticks; + const _260: Ticked.Ticked[] = [tick(4)]; + if (rt.usizeRem(data.length, 2) === 0) { + _266 = new rt.Borrowed(ticks); + } else { + _266 = [tick(7)]; + } + new Runs.Runs(_246, _256, _258, _260, _266, [[tick(5), tick(6)]], option_map$12l9avg(rt.byteSliceFirst(data), (_210: rt.u8): Ticked.Ticked[] => { + return [tick(~_210 & 0xff)]; + }))[Symbol.dispose](); + const _292: rt.usize = rt.usizeRem(data.length, 3); + if (_292 === 0) { + run3 = { tag: "Listed", _0: [tick(8)] } as generics_Run.Run; + } else if (_292 === 1) { + run3 = { tag: "Fixed", array: [tick(9), tick(10)] } as generics_Run.Run; + } else { + run3 = { tag: "Empty" } as generics_Run.Run; + } + drop$generics_Run_generics_Ticked(run3); + rt.dropAll(ticks); + const _315: rt.RefCell = rt.refCellBorrow(log.value); + rt.iterExtendBytes(out, rt.iterSlice(rt.byteSliceView(rt.byteVecSlice(_315.value))), undefined, true); + rt.refRelease(_315); + log[Symbol.dispose](); +} + //# sourceMappingURL=generics.ts.map diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 6bfb89df2..f59dc2e82 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -27,7 +27,7 @@ import { fields as fields_fields } from "./fields.ts"; import { floats, mulAdds as floats_mulAdds, formats as floats_formats, parses as floats_parses } from "./floats.ts"; import { ints, strings, derived, written as fmt_written, counts as fmt_counts, rounding, panics as fmt_panics, wrapped as fmt_wrapped, collections, enums, iters as fmt_iters, writes as fmt_writes } from "./fmt.ts"; import { folds } from "./folds.ts"; -import { methods } from "./generics.ts"; +import { methods, runs } from "./generics.ts"; import { values as hashes_values, random, bytes as hashes_bytes } from "./hashes.ts"; import { hints, reserves } from "./hints.ts"; import { holds } from "./holds.ts"; @@ -252,12 +252,14 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) partWritten(data87, out88); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["pointers::aimed", (_2188: rt.u8, data88: rt.ByteSlice, out89: rt.ByteVec): undefined => { 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], ["results::results", results_results as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["fields::fields", fields_fields as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["strs::gets", gets as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] 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], ["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], ["generics::runs", (_2189: rt.u8, data89: rt.ByteSlice, out90: rt.ByteVec): undefined => { + runs(data89, out90); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["borrows::guards", (_2190: rt.u8, data90: rt.ByteSlice, out91: rt.ByteVec): undefined => { + guards(data90, out91); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["results::results", results_results as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["fields::fields", fields_fields as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["strs::gets", gets as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["borrows::maps", (_2191: rt.u8, data91: rt.ByteSlice, out92: rt.ByteVec): undefined => { + borrows_maps(data91, out92); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["locks::mapped", (_2192: rt.u8, data92: rt.ByteSlice, out93: rt.ByteVec): undefined => { + mapped(data92, out93); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; } diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts index 7afb41da6..70fe8186f 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -16,6 +16,9 @@ import type * as RcShared from "./counts.RcShared.ts"; import type * as durations_Window from "./durations.Window.ts"; import type * as Couple from "./fields.Couple.ts"; import type * as Either from "./generics.Either.ts"; +import * as Fixed from "./generics.Fixed.ts"; +import type * as generics_Run from "./generics.Run.ts"; +import type * as Ticked from "./generics.Ticked.ts"; import * as Wrap from "./generics.Wrap.ts"; import type * as Bumped from "./iters.Bumped.ts"; import type * as joins_Logged from "./joins.Logged.ts"; @@ -322,6 +325,14 @@ export function copy$generics_Either_u8_shapes_Point(v: Either.Either): Fixed.Fixed { + return new Fixed.Fixed(copy$array_u16(v.pair as rt.u16[]), v.tag); +} + +export function copy$generics_Fixed_u8(v: Fixed.Fixed): Fixed.Fixed { + return new Fixed.Fixed(copy$array_u8(v.pair as Uint8Array), v.tag); +} + export function copy$generics_Wrap_shapes_Point(v: Wrap.Wrap): Wrap.Wrap { return new Wrap.Wrap(copy$shapes_Point(v.value), v.count); } @@ -971,6 +982,14 @@ export function drop$cell_RefCell_Vec_sync_Arc_counts_ArcReleasing(value: rt.Ref rt.dropAll(value.value); } +export function drop$generics_Run_generics_Ticked(_1: generics_Run.Run): void { + if (_1.tag === "Listed") { + rt.dropAll(_1._0 as Ticked.Ticked[]); + } else if (_1.tag === "Fixed") { + rt.dropAll(_1.array as Ticked.Ticked[]); + } +} + export function drop$pointers_List_String(_1: List.List): void { List.drop$ops_Drop_String(_1); } diff --git a/ts/fixtures/lang/expected/strs.Counted.ts b/ts/fixtures/lang/expected/strs.Counted.ts index 5be43d361..e96c71263 100644 --- a/ts/fixtures/lang/expected/strs.Counted.ts +++ b/ts/fixtures/lang/expected/strs.Counted.ts @@ -4,16 +4,16 @@ import * as rt from "./rt.ts"; /** A crate's own iterator over `items`, which counts each `next` it is asked. */ export interface Counted { - items: T[]; + items: rt.SliceOf; nexts: rt.Cell; } export function next$iter_Iterator_String(self: Counted): string | rt.Done { rt.cellSet(self.nexts, rt.u8Add(self.nexts.v, 1)); - const _8: [string, string[]] | undefined = rt.sliceSplitFirst(self.items); + const _8: [string, string[]] | undefined = rt.sliceSplitFirst(self.items as string[]); if (_8 !== undefined) { const val: [string, string[]] = _8; - self.items = val[1]; + (self.items as string[]) = val[1]; return val[0]; } return rt.DONE; @@ -21,10 +21,10 @@ export function next$iter_Iterator_String(self: Counted): string | rt.Do export function next$iter_Iterator_char(self: Counted): rt.char | rt.Done { rt.cellSet(self.nexts, rt.u8Add(self.nexts.v, 1)); - const _8: [rt.char, rt.char[]] | undefined = rt.sliceSplitFirst(self.items); + const _8: [rt.char, rt.char[]] | undefined = rt.sliceSplitFirst(self.items as rt.char[]); if (_8 !== undefined) { const val: [rt.char, rt.char[]] = _8; - self.items = val[1]; + (self.items as rt.char[]) = val[1]; return val[0]; } return rt.DONE; @@ -32,10 +32,10 @@ export function next$iter_Iterator_char(self: Counted): rt.char | rt.Do export function next$iter_Iterator_ref_str(self: Counted): string | rt.Done { rt.cellSet(self.nexts, rt.u8Add(self.nexts.v, 1)); - const _8: [string, string[]] | undefined = rt.sliceSplitFirst(self.items); + const _8: [string, string[]] | undefined = rt.sliceSplitFirst(self.items as string[]); if (_8 !== undefined) { const val: [string, string[]] = _8; - self.items = val[1]; + (self.items as string[]) = val[1]; return val[0]; } return rt.DONE; diff --git a/ts/fixtures/lang/src/generics.rs b/ts/fixtures/lang/src/generics.rs index 1663056b5..5ac227ee2 100644 --- a/ts/fixtures/lang/src/generics.rs +++ b/ts/fixtures/lang/src/generics.rs @@ -1,5 +1,9 @@ //! Methods on generic structs and enums, each instance its own method. +use std::borrow::Cow; +use std::cell::RefCell; +use std::rc::Rc; + use crate::fmt::{Pair, put}; use crate::shapes::{Area, Meters, Point, Shape, Track}; @@ -187,3 +191,195 @@ pub fn reset(xs: &mut [X]) { *x = X::default(); } } + +/// A generic type holding runs of its parameter in each form JS keeps a run of bytes +/// apart in, which only an instance decides. +#[derive(Clone, Debug, PartialEq)] +pub struct Runs<'a, T: Clone> { + pub array: [T; 3], + pub list: Vec, + pub view: &'a [T], + pub boxed: Box<[T]>, + pub cow: Cow<'a, [T]>, + pub pairs: Vec<[T; 2]>, + pub maybe: Option>, +} + +/// An enum holding a run of its parameter in a variant. +#[derive(Clone, Debug, PartialEq)] +pub enum Run { + Listed(Vec), + Fixed { array: [T; 2] }, + Empty, +} + +impl Runs<'_, T> { + fn total(&self) -> usize { + self.array.len() + self.list.len() + self.view.len() + self.boxed.len() + self.cow.len() + self.pairs.len() + } + + fn push(&mut self, item: T) { + self.list.push(item); + self.cow.to_mut().push(item); + self.pairs.push([item; 2]); + self.array.rotate_left(1); + self.array[2] = item; + self.boxed[0] = item; + if let Some(maybe) = &mut self.maybe { + maybe.push(item); + } + } + + fn run(&self) -> Run { + match self.list.len() % 3 { + 0 => Run::Listed(self.list.clone()), + 1 => Run::Fixed { + array: [self.array[0], self.array[2]], + }, + _ => Run::Empty, + } + } +} + +impl Run { + fn first(&self) -> Option { + match self { + Run::Listed(list) => list.first().copied(), + Run::Fixed { array } => Some(array[0]), + Run::Empty => None, + } + } +} + +/// A generic type JS copies, holding an array of its parameter. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Fixed { + pub pair: [T; 2], + pub tag: u8, +} + +/// `fixed` with its pair swapped, in a copy of it. +fn swapped(fixed: Fixed) -> Fixed { + let mut copy = fixed; + copy.pair.swap(0, 1); + copy +} + +/// A generic type lending a run of its parameter, which it writes through, and a function +/// of one. +struct Lends<'a, T> { + run: &'a mut [T], + last: fn(&[T]) -> Option<&T>, +} + +/// Writes `item` over each element of `run`, through a `&mut` to a field. +fn fill(run: &mut [T], item: T) { + for x in run { + *x = item; + } +} + +/// [`Runs`] at bytes and at another element: made, written through its fields and +/// through `&mut`s to them, copied, compared, and printed. +macro_rules! runs_of { + ($data:expr, $out:expr, $ty:ty) => {{ + let data: Vec<$ty> = $data.iter().map(|&b| <$ty>::from(b)).collect(); + let n = data.first().copied().unwrap_or_default(); + let mut runs = Runs { + array: [n; 3], + list: data.clone(), + view: &data, + boxed: data.clone().into_boxed_slice(), + cow: Cow::Borrowed(&data), + pairs: Vec::new(), + maybe: (data.len() % 2 == 0).then(Vec::new), + }; + let before = runs.clone(); + for &x in data.iter().take(3) { + runs.push(x); + } + if let Some(pair) = runs.pairs.first_mut() { + fill(pair, n); + } + fill(&mut runs.array[1..], <$ty>::from(7u8)); + let mut taken = std::mem::take(&mut runs.list); + let lent = Lends { + run: &mut taken, + last: <[$ty]>::last, + }; + let last = (lent.last)(runs.view).copied(); + if let Some(x) = lent.run.last_mut() { + *x = n; + } + fill(lent.run, <$ty>::from(3u8)); + let run = runs.run(); + let fixed = Fixed { pair: [n, n], tag: 1 }; + let mut copy = fixed; + copy.pair[0] = <$ty>::from(9u8); + let swapped = swapped(copy); + put( + $out, + &format!( + "{runs:?} {before:?} {taken:?} {run:?} {fixed:?} {copy:?} {swapped:?} {} {} {:?} {last:?}", + runs.total(), + runs == before, + run.first(), + ), + ); + }}; +} + +/// Logs its id as it drops, and as it is cloned, the id with the high bit set. +struct Ticked { + id: u8, + log: Rc>>, +} + +impl Clone for Ticked { + fn clone(&self) -> Self { + self.log.borrow_mut().push(0x80 | self.id); + Self { + id: self.id, + log: self.log.clone(), + } + } +} + +impl Drop for Ticked { + fn drop(&mut self) { + self.log.borrow_mut().push(self.id); + } +} + +/// [`Runs`], [`Run`], and [`Fixed`] at `u8`, whose runs JS keeps as bytes, and at +/// `u16`, then [`Runs`] and [`Run`] of values that drop, in the order of their fields. +pub fn runs(data: &[u8], out: &mut Vec) { + runs_of!(data, out, u8); + runs_of!(data, out, u16); + let log = Rc::new(RefCell::new(Vec::new())); + let tick = |id: u8| Ticked { id, log: log.clone() }; + let ticks: Vec = data.iter().map(|&id| tick(id)).collect(); + let runs = Runs { + array: [tick(1), tick(2), tick(3)], + list: ticks.clone(), + view: &ticks, + boxed: Box::new([tick(4)]), + cow: match data.len() % 2 { + 0 => Cow::Borrowed(&ticks), + _ => Cow::Owned(vec![tick(7)]), + }, + pairs: vec![[tick(5), tick(6)]], + maybe: data.first().map(|&id| vec![tick(!id)]), + }; + drop(runs); + let run = match data.len() % 3 { + 0 => Run::Listed(vec![tick(8)]), + 1 => Run::Fixed { + array: [tick(9), tick(10)], + }, + _ => Run::Empty, + }; + drop(run); + drop(ticks); + out.extend(log.borrow().iter()); +} diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 7edd26021..80884713f 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -268,6 +268,7 @@ fn cases() -> Vec<(&'static str, Case)> { ("arrays::flattened", arrays::flattened), ("args::args", args::args), ("returns::returns", returns::returns), + ("generics::runs", |_, data, out| generics::runs(data, out)), ("borrows::guards", |_, data, out| borrows::guards(data, out)), ("results::results", results::results), ("fields::fields", fields::fields), diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 352006d9e..fd12576bd 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` - Refusals: 218 -- Function instances: 274 +- Function instances: 271 - Generic functions no instance reached, lowered over their type parameters: 13 ## By construct @@ -57,7 +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 mapped guard of `_`, which JS can't write in place | fixtures/reject/src/lib.rs:2154: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 | @@ -303,7 +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 mapped guard of `_`, which JS can't write in place | `{closure}` | fixtures/reject/src/lib.rs:2154: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 | @@ -694,7 +694,7 @@ The type or module each refused type or path belongs to.
comparing pointers to `_`, each a place JS makes of its own (2) - fixtures/reject/src/lib.rs:598:2: comparing pointers to `u32`, each a place JS makes of its own -- fixtures/reject/src/lib.rs:2165:2: comparing pointers to `u32`, each a place JS makes of its own +- fixtures/reject/src/lib.rs:2147:2: comparing pointers to `u32`, each a place JS makes of its own
@@ -865,7 +865,7 @@ 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 +- fixtures/reject/src/lib.rs:2154:10: a mapped guard of `{closure@fixtures/reject/src/lib.rs:2153:38: 2153:50}`, which JS can't write in place
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 59f89707c..f194a04cf 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -78,7 +78,7 @@ unsupported call to `std::alloc::dealloc` at fixtures/reject/src/lib.rs:572:3 a raw pointer to `std::vec::Vec` behind a reference, which is the object and not where it is kept at fixtures/reject/src/lib.rs:579:10 union `Bits`, whose fields overlap in `u32` and `f64`, which JS keeps apart at fixtures/reject/src/lib.rs:590:10 comparing pointers to `u32`, each a place JS makes of its own at fixtures/reject/src/lib.rs:598:2 -comparing pointers to `u32`, each a place JS makes of its own at fixtures/reject/src/lib.rs:2165:2 +comparing pointers to `u32`, each a place JS makes of its own at fixtures/reject/src/lib.rs:2147:2 a raw pointer to `(u32, u32)` in `Span2`, which the crate may put another object in place of at fixtures/reject/src/lib.rs:610:10 a raw pointer to `(u32, u32)` in a variable assigned again while it may point there at fixtures/reject/src/lib.rs:618:10 a raw pointer to `(u32, u32)` in a variable assigned again while it may point there at fixtures/reject/src/lib.rs:626:10 @@ -198,7 +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 +a mapped guard of `{closure@fixtures/reject/src/lib.rs:2153:38: 2153:50}`, which JS can't write in place at fixtures/reject/src/lib.rs:2154: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/mistyped.toml b/ts/fixtures/reject/mistyped.toml deleted file mode 100644 index 51d11dc8e..000000000 --- a/ts/fixtures/reject/mistyped.toml +++ /dev/null @@ -1,4 +0,0 @@ -# A typing gap translation doesn't refuse, which `tsc` fails at the Rust the source map -# names: `mistyped.txt` holds the errors. -package = "reject-fixture" -roots = ["mistyped"] diff --git a/ts/fixtures/reject/mistyped.txt b/ts/fixtures/reject/mistyped.txt deleted file mode 100644 index 612713cfb..000000000 --- a/ts/fixtures/reject/mistyped.txt +++ /dev/null @@ -1,2 +0,0 @@ -lib.Rows.ts:22:20 doesn't type-check, which is a bug in rust2-ts: error TS2339: Property 'data' does not exist on type 'u8[]'. at fixtures/reject/src/lib.rs:2153:3 -lib.ts:8:47 doesn't type-check, which is a bug in rust2-ts: error TS2740: Type 'ByteVec' is missing the following properties from type 'u8[]': pop, push, concat, join, and 28 more. at fixtures/reject/src/lib.rs:2159:4 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 42ebc943a..279bfe6e7 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -2141,24 +2141,6 @@ pub fn generic_park_rebound(mut w: Parking, next: Parking) -> i16 { unsafe { (*p).0.get() + w.park.0.get() } } -/// A generic type's `Vec`, typed `T[]` though its `u8` instance holds an `rt.ByteVec`: -/// translation writes output `tsc` rejects, and fails at the Rust it maps to. -pub struct Rows { - pub items: Vec, -} - -impl Rows { - pub fn first(&self) -> T { - self.items[0] - } -} - -pub fn mistyped(bytes: Vec, words: Vec) -> u32 { - let a = Rows { items: bytes }; - let b = Rows { items: words }; - a.first() as u32 + b.first() as u32 -} - /// An `Option` of pointers to a number, each an `rt.Place` JS makes of its own. pub fn optional_places_compared(n: &mut u32) -> bool { let p = std::ptr::NonNull::from(&mut *n); diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index b0d1a0f40..b93329416 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -131,6 +131,18 @@ export const DANGLING_UNIT: Place = { v: undefined }; */ export type Ptr = T | Place | ByteSlice; +/** A generic type's `[T; N]`: the array, or the `Uint8Array` of a `[u8; N]`. */ +export type ArrayOf = T[] | Uint8Array; + +/** A generic type's `[T]`, as behind a reference: the array, or the `ByteSlice` of a `[u8]`. */ +export type SliceOf = T[] | ByteSlice; + +/** A generic type's `Vec`: the array, or the `ByteVec` of a `Vec`. */ +export type VecOf = T[] | ByteVec; + +/** A generic type's `Cow<[T]>`: the `Cow`, or the `ByteCow` of a `Cow<[u8]>`. */ +export type CowOf = Cow | ByteCow; + /** * `ptr::write` of `value` through a pointer to an object: `value` copied into it, one * object deep, so every pointer to it sees the write. diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index d82143042..b9e990ed2 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -533,12 +533,20 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { let sym = self.instance(Instance::mono(tcx, dtor.did)); steps.push(StmtKind::Expr(Expr::Sym(sym).call(vec![Expr::This])).at(None)); } + // Only an instance whose parameters drop runs the glue, so none is a byte: a field + // whose definition's type an instance decides is read as an array of them holds it. + let glue = std::mem::replace(&mut self.glue, true); for (field, &id) in adt.non_enum_variant().fields.iter().zip(fields) { let ty = tcx.type_of(field.did).instantiate_identity().skip_norm_wip(); - if let Some(dropped) = self.drop_value(Translator::read_field(Expr::This, id), ty, span) { + let read = match self.instanced_fields.contains_key(&field.did) { + true => Expr::As(Box::new(Translator::read_field(Expr::This, id)), self.ty(ty, span)), + false => Translator::read_field(Expr::This, id), + }; + if let Some(dropped) = self.drop_value(read, ty, span) { steps.push(StmtKind::Expr(dropped).at(None)); } } + self.glue = glue; let sym = self.program.sym(Symbol { module: self.module_of(adt.did()), base: "[Symbol.dispose]".into(), diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 1fa15b3eb..e54baba62 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -1763,12 +1763,13 @@ fn continued(ty: Ty<'_>) -> Ty<'_> { } } -/// Whether an assignment can write `e`: a path, an element, or a member of one. +/// Whether an assignment can write `e`: a path, an element, or a member of one, through a +/// cast, as a generic type's field is read as its instance holds it. fn assignable(e: &Expr) -> bool { match e { _ if super::place::split_target(e).is_some() => true, Expr::Index(..) => true, - Expr::Member(base, _) | Expr::Located(_, base) => assignable(base), + Expr::Member(base, _) | Expr::Located(_, base) | Expr::As(base, _) => assignable(base), e => e.is_path(), } } diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index b2c1084d0..0c0675494 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -193,10 +193,11 @@ pub struct Translator<'a, 'tcx> { instances: rustc_data_structures::fx::FxHashMap, SymId>, queue: VecDeque<(Instance<'tcx>, SymId)>, adts: rustc_data_structures::fx::FxHashMap, - /// The fields of generic types whose definition types a pointer as an `rt.Ptr`, which - /// an instance's read casts to what it holds, with that type where a function type in - /// it takes one, which an instance's value is cast to. - ptr_fields: rustc_data_structures::fx::FxHashMap>, + /// The fields of generic types whose definition types a form only an instance decides, + /// such as an `rt.Ptr` or an `rt.VecOf`, which an instance's read casts to what it + /// holds, with that type where a function type in it takes one, which an instance's + /// value is cast to. + instanced_fields: rustc_data_structures::fx::FxHashMap>, /// Source files by name, as indexes into `program.sources`. sources: rustc_data_structures::fx::FxHashMap>, failed: bool, @@ -249,6 +250,9 @@ pub struct Translator<'a, 'tcx> { pub coroutines: rustc_data_structures::fx::FxHashMap, mir::coroutine::Info<'tcx>>, /// Whether [`Self::ty`] is typing a variable: see [`Self::held_ty`]. held: bool, + /// Whether [`Self::ty`] is typing a generic class's drop glue, which only an instance + /// whose parameters drop runs, so none is a byte. + glue: bool, /// Where the crate first reached each instance of std's that lowers from its MIR, which /// refuses there: its own spans are std's. sites: rustc_data_structures::fx::FxHashMap, Span>, @@ -455,7 +459,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { instances: Default::default(), queue: VecDeque::new(), adts: Default::default(), - ptr_fields: Default::default(), + instanced_fields: Default::default(), sources: Default::default(), failed: false, env: TypingEnv::fully_monomorphized(), @@ -482,6 +486,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { compared, comparing: Default::default(), held: false, + glue: false, sites: Default::default(), site: None, bindings: Default::default(), @@ -625,6 +630,18 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { self.polymorphic() && matches!(ty.kind(), ty::Param(_) | ty::Alias(..)) } + /// Whether `ty` is a type parameter, or a projection from one, in a generic type's + /// definition, which only an instance decides. + pub fn open(&self, ty: Ty<'tcx>) -> bool { + !self.polymorphic() && ty.has_param() && matches!(ty.kind(), ty::Param(_) | ty::Alias(..)) + } + + /// Whether only an instance decides whether `elem`, a run's element, is a byte, which + /// JS keeps a run of apart. + fn open_elem(&self, elem: Ty<'tcx>) -> bool { + !self.glue && self.open(elem) + } + pub fn typing_env_pub(&self) -> TypingEnv<'tcx> { self.typing_env() } @@ -1017,8 +1034,9 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } // Its fields' types are refused where they are written, whatever reached it. let held = std::mem::replace(&mut self.held, false); + let glue = std::mem::replace(&mut self.glue, false); let info = self.define(adt, span); - self.held = held; + (self.held, self.glue) = (held, glue); info } @@ -1409,6 +1427,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { ty::RawPtr(inner, _) => self.pointer_ty(*inner, span), ty::Ref(..) if bytes_ref(ty) => Type::Rt("ByteSlice", vec![]), ty::Ref(_, inner, _) => self.ty(*inner, span), + ty::Array(elem, _) if self.open_elem(*elem) => Type::Rt("ArrayOf", vec![self.ty(*elem, span)]), + ty::Slice(elem) if self.open_elem(*elem) => Type::Rt("SliceOf", vec![self.ty(*elem, span)]), ty::Array(elem, _) => match elem.kind() { ty::Uint(ty::UintTy::U8) => Type::Builtin("Uint8Array"), _ => Type::Array(Box::new(self.ty(*elem, span))), @@ -1558,6 +1578,9 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { "Result", vec![self.ty(args.type_at(0), span), self.ty(args.type_at(1), span)], ), + library::Std::Vec if self.open_elem(args.type_at(0)) => { + Type::Rt("VecOf", vec![self.ty(args.type_at(0), span)]) + } library::Std::Vec => match args.type_at(0).kind() { ty::Uint(ty::UintTy::U8) => Type::Rt("ByteVec", vec![]), _ => Type::Array(Box::new(self.ty(args.type_at(0), span))), @@ -1566,6 +1589,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { library::Std::Cow if library::string(tcx, Ty::new_adt(tcx, adt, args)) => Type::Builtin("string"), library::Std::Cow if let Some(elem) = library::cow_slice(tcx, Ty::new_adt(tcx, adt, args)) => { match elem.kind() { + _ if self.open_elem(elem) => Type::Rt("CowOf", vec![self.ty(elem, span)]), ty::Uint(ty::UintTy::U8) => Type::Rt("ByteCow", vec![]), _ => Type::Rt("Cow", vec![self.ty(elem, span)]), } @@ -1747,19 +1771,21 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } /// The TypeScript type of `field` in its type's definition, with `identity` its own - /// parameters, noting a field that holds an `rt.Ptr` for [`Self::held_field`]. + /// parameters, noting a field that holds a form only an instance decides for + /// [`Self::held_field`]. fn defined_field_ty(&mut self, field: &ty::FieldDef, identity: GenericArgsRef<'tcx>, span: Span) -> Type { let ty = self.ty(field.ty(self.tcx, identity).skip_norm_wip(), span); - let ptr = |t: &Type| matches!(t, Type::Rt("Ptr", _)); - if ty.any(&ptr) { - self.ptr_fields.insert(field.did, ty.takes(&ptr).then(|| ty.clone())); + let instanced = |t: &Type| matches!(t, Type::Rt("Ptr" | "ArrayOf" | "SliceOf" | "VecOf" | "CowOf", _)); + if ty.any(&instanced) { + self.instanced_fields + .insert(field.did, ty.takes(&instanced).then(|| ty.clone())); } ty } /// `value`, for `field` of an instance of `adt` with `args`, cast to the field's type in - /// the definition at those arguments where a function type in it takes an `rt.Ptr`: a - /// function taking what the instance's pointer is takes no other form of one. + /// the definition at those arguments where a function type in it takes a form only an + /// instance decides: a function taking what the instance holds takes no other form. pub fn field_value( &mut self, value: ts::Expr, @@ -1768,7 +1794,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { args: GenericArgsRef<'tcx>, span: Span, ) -> ts::Expr { - let Some(Some(defined)) = self.ptr_fields.get(&field).cloned() else { + let Some(Some(defined)) = self.instanced_fields.get(&field).cloned() else { return value; }; let params: Vec<(String, Type)> = (self.tcx.generics_of(adt).own_params.iter()) @@ -1785,9 +1811,9 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } /// `read`, of `field` of an instance with `args`, cast to what the instance holds there - /// where the definition types a pointer in it as an `rt.Ptr`. + /// where the definition types a form in it that only an instance decides. pub fn held_field(&mut self, read: ts::Expr, field: DefId, args: GenericArgsRef<'tcx>, span: Span) -> ts::Expr { - if !self.ptr_fields.contains_key(&field) { + if !self.instanced_fields.contains_key(&field) { return read; } let ty = self.field_ty(field, args); diff --git a/ts/src/lower/pointer.rs b/ts/src/lower/pointer.rs index 8aa6e1c13..4020436c3 100644 --- a/ts/src/lower/pointer.rs +++ b/ts/src/lower/pointer.rs @@ -119,12 +119,11 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { if self.polymorphic() || !ty.has_param() { return false; } - let open = |ty: Ty<'tcx>| matches!(ty.kind(), ty::Param(_) | ty::Alias(..)); let ty = self.uninit_inner(ty); match ty.kind() { - ty::Array(elem, _) => open(*elem), + ty::Array(elem, _) => self.open(*elem), ty::Adt(adt, _) => self.bound_drops(adt.did()).is_some(), - _ => open(ty), + _ => self.open(ty), } } diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index a181b5d11..41e37c162 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -439,10 +439,6 @@ export const run = (input: rt.ByteSlice) => script(rt.byteSliceView(input)); fn reject() { let (out, output) = translate("reject"); rejected(&out, &output, &fixture("reject").join("expected.txt")); - let out = scratch().join("reject").join("mistyped"); - let config = fixture("reject").join("mistyped.toml"); - let output = driver("reject", &config, &["--out".as_ref(), out.as_ref()], "build"); - rejected(&out, &output, &fixture("reject").join("mistyped.txt")); } /// Bindings stand in for what translation refuses, `bytes::Bytes` and the crate's own