diff --git a/quest/m3/README.md b/quest/m3/README.md index f20b259dc..8b1975b4d 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -34,6 +34,5 @@ generic std gap is planned here even when moq never calls it. - [A VecDeque's Debug](/quest/m3/ts-deque-debug.md) - `{:?}` of a `VecDeque` translates, writing std's list - [A parameter read only where lowering leaves nothing](/quest/m3/ts-unread-params.md) - an instance whose lowering drops every read of a parameter marks it unused, so `tsc` accepts it - [std's impls of its zero-sized types](/quest/m3/ts-zero-sized-impls.md) - `PhantomData`'s derived impls translate, and `()` is a hash or B-tree key -- [An array's map](/quest/m3/ts-array-map.md) - `<[T; N]>::map` translates, calling its closure on each element in order - [Array keys a collection holds](/quest/m3/ts-array-keys.md) - collections of `[T; N]` keys type-check - [Zip's next_back in constant time](/quest/m3/ts-zip-back.md) - a reversed zip of random-access iterators skips the longer side's excess at once diff --git a/quest/m3/ts-array-map.md b/quest/m3/ts-array-map.md deleted file mode 100644 index 501c98a74..000000000 --- a/quest/m3/ts-array-map.md +++ /dev/null @@ -1,16 +0,0 @@ -# [S] An array's map - -## Goal - -`<[T; N]>::map` translates for every element type, its closure called on each element in -order, proven by a differential test against native Rust that covers `[u8; N]` results. - -## Plan - -Reproduced on `955ac19f`: `[bool; 3].map(u8::from)` is refused at its span as an -unsupported call to `std::array::::map`. A `[u8; N]` result is a -`Uint8Array`, as `array::from_fn`'s is. - -Found by [#302](https://github.com/moq-dev/rust2/pull/302). - -Public API: the translator's output. diff --git a/ts/fixtures/lang/expected/arrays.ts b/ts/fixtures/lang/expected/arrays.ts index 6b011958f..d124e767e 100644 --- a/ts/fixtures/lang/expected/arrays.ts +++ b/ts/fixtures/lang/expected/arrays.ts @@ -1,7 +1,8 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$u32s, copy$u8s } from "./lib.ts"; +import { copy$u32s, copy$u8s, copy$u8ss } from "./lib.ts"; +import { map$1j8xzu6, map$0rbsrz6 } from "./core/option.ts"; /** Each byte an operation, its value the operand; each puts what it read. */ export function fromFns(data: rt.ByteSlice, out: rt.ByteVec): void { @@ -95,6 +96,234 @@ export function counted$5(op: rt.u8): rt.usize[] { }); } +/** + * Arrays `map` makes, calling its closure on each element in order; each byte an + * operation, its value the operand. From bytes and to them, of none at all, through what + * the closure captured by reference and by move, of `Option`s whose `None` is `rt.None`, + * and of arrays, each element the closure's own to change. + */ +export function maps(data: rt.ByteSlice, out: rt.ByteVec): void { + let s!: string; + for (const op of rt.byteSliceView(data)) { + const _10: rt.u8 = rt.u8Rem(op, 5); + if (_10 === 0) { + const seen: rt.ByteVec = new rt.ByteVec(); + const bytes: Uint8Array = Uint8Array.of(op, op ^ 1, op ^ 2, op ^ 3); + const wide: rt.u16[] = rt.arrayMap(bytes, (b2: rt.u8): rt.u16 => { + rt.byteVecPush(seen, b2); + return ((((b2 as rt.u16)) << 8) & 0xffff) | op as rt.u16; + }); + const narrow: Uint8Array = rt.bytesMap(wide, (w3: rt.u16): rt.u8 => { + return (w3 >> 4) & 0xff; + }); + const same: Uint8Array = rt.bytesMap(narrow, (b3: rt.u8): rt.u8 => { + return rt.u8WrappingMul(b3, op); + }); + const words: rt.u32[] = rt.arrayMap([op as rt.u32, 7, 9], (w4: rt.u32): rt.u32 => { + return rt.u32WrappingMul(w4, 16777619); + }); + const _31: rt.ByteSlice = rt.byteSliceFrom(bytes); + const _33: rt.ByteSlice = rt.byteSliceFrom(narrow); + const _34: rt.ByteSlice = rt.byteSliceFrom(same); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(_31), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(wide, f, rt.u16Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(_33), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(_34), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(words, f, rt.u32Debug), (f: rt.Formatter) => rt.fmtList(rt.byteVecView(seen), f, rt.u8Debug)]; + s = rt.fmtFormat([args2[0], " ", args2[1], " ", args2[2], " ", args2[3], " ", args2[4], " ", args2[5]]); + } else if (_10 === 1) { + const _46: rt.u16[] = rt.arrayMap(Uint8Array.of(), (a0: rt.u8): rt.u16 => { + return a0 as rt.u16; + }); + const _47: Uint8Array = rt.bytesMap([], (w2: rt.u16): rt.u8 => { + return w2 & 0xff; + }); + const _48: string[] = rt.arrayMap([], (n: rt.u32): string => { + return rt.fmtToString((f: rt.Formatter) => rt.u32Display(n, f)); + }); + const _53: rt.ByteSlice = rt.byteSliceFrom(_47); + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(_46, f, rt.u16Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(_53), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(_48, f, rt.fmtStr)]; + s = rt.fmtFormat([args4[0], " ", args4[1], " ", args4[2]]); + } else if (_10 === 2) { + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.u8Display(op, f)]; + const captured = rt.fmtFormat(["w", args6[0]]); + const words2: string[] = rt.arrayMap(Uint8Array.of(1, 2, 3), (i: rt.u8): string => { + const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, captured), (f: rt.Formatter) => rt.u8Display(i, f)]; + return rt.fmtFormat([args16[0], args16[1]]); + }); + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(words2, f, rt.fmtStr)]; + const shown: string = rt.fmtFormat([args8[0]]); + const _89: rt.ByteSlice = rt.byteSliceFrom(rt.bytesMap(words2, (w: string): rt.u8 => { + return rt.u8Add(rt.stringLen(w) & 0xff, rt.u8Rem(op, 3)); + })); + const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, shown), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(_89), f, rt.u8Debug)]; + s = rt.fmtFormat([args10[0], " ", args10[1]]); + } else if (_10 === 3) { + const options: Array = [op, undefined, rt.u8WrappingAdd(op, 60)]; + const nested: Array = rt.arrayMap(options, (o: rt.u8 | undefined): rt.u8 | undefined | rt.None => { + return map$0rbsrz6(o, (b: rt.u8): rt.u8 | undefined => { + return rt.u8CheckedAdd(b, 200); + }); + }); + const flat: Array = rt.arrayMap(nested, (o2: rt.u8 | undefined | rt.None): rt.u8 | undefined => { + if (o2 === rt.None) { + return 0; + } + return o2; + }); + const units: Array = rt.arrayMap(nested, (o3: rt.u8 | undefined | rt.None): undefined | rt.None => { + return map$1j8xzu6(o3, (_2: rt.u8 | undefined): undefined => {}); + }); + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(options, f, (value: rt.u8 | undefined, f: rt.Formatter) => rt.fmtOption(value, f, rt.u8Debug)), (f: rt.Formatter) => rt.fmtList(nested, f, (value: rt.u8 | undefined | rt.None, f: rt.Formatter) => rt.fmtOption(value, f, (value: rt.u8 | undefined, f: rt.Formatter) => rt.fmtOption(value, f, rt.u8Debug), rt.None)), (f: rt.Formatter) => rt.fmtList(flat, f, (value: rt.u8 | undefined, f: rt.Formatter) => rt.fmtOption(value, f, rt.u8Debug)), (f: rt.Formatter) => rt.fmtList(units, f, (value: undefined | rt.None, f: rt.Formatter) => rt.fmtOption(value, f, rt.fmtUnit, rt.None))]; + s = rt.fmtFormat([args12[0], " ", args12[1], " ", args12[2], " ", args12[3]]); + } else { + const grid: Uint8Array[] = [Uint8Array.of(op, 1), Uint8Array.of(2, 3), Uint8Array.of(4, op)]; + const flipped: Uint8Array[] = rt.arrayMap(grid, (row: Uint8Array): Uint8Array => { + row = copy$u8s(row); + row[0] = row[0] ^ 255; + rt.byteSliceView(rt.byteSliceFrom(row)).reverse(); + return copy$u8s(row); + }); + const sums: rt.u16[] = rt.arrayMap(flipped, (row2: Uint8Array): rt.u16 => { + return rt.u16Add(row2[0] as rt.u16, row2[1] as rt.u16); + }); + const same2: Uint8Array[] = copy$u8ss(rt.arrayMap(grid, (row3: Uint8Array): Uint8Array => { + return row3; + })); + const _124: rt.usize = rt.usizeRem(op as rt.usize, 3); + if (!(_124 < 3)) { + rt.panic("index out of bounds: the len is " + 3 + " but the index is " + _124); + } + same2[_124][0] = same2[_124][0] ^ 128; + const _134: rt.u64[] = shifted$3(op); + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(grid, f, (value: Uint8Array, f: rt.Formatter) => rt.fmtList(value, f, rt.u8Debug)), (f: rt.Formatter) => rt.fmtList(flipped, f, (value: Uint8Array, f: rt.Formatter) => rt.fmtList(value, f, rt.u8Debug)), (f: rt.Formatter) => rt.fmtList(sums, f, rt.u16Debug), (f: rt.Formatter) => rt.fmtList(same2, f, (value: Uint8Array, f: rt.Formatter) => rt.fmtList(value, f, rt.u8Debug)), (f: rt.Formatter) => rt.fmtList(_134, f, rt.u64Debug)]; + s = rt.fmtFormat([args14[0], " ", args14[1], " ", args14[2], " ", args14[3], " ", args14[4]]); + } + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(s)); + rt.byteVecPush(out, 10); + } +} + +/** An array as long as `N` says, mapped by a function. */ +export function shifted$3(op: rt.u8): rt.u64[] { + return rt.arrayMap(rt.bytes(3).fill(op), (a0: rt.u8): rt.u64 => { + return a0 as rt.u64; + }); +} + +/** + * Arrays' elements lent by `each_ref` and `each_mut`, each byte an operation, its value + * the operand: bytes, wide integers, and strings, each lent as its place, arrays of bytes + * as their views, and other arrays as themselves. Writes through each land in the array. + */ +export function lent(data: rt.ByteSlice, out: rt.ByteVec): void { + const bytes: Uint8Array = rt.bytes(3); + const wide: rt.u16[] = Array.from({ length: 2 }, (): rt.u16 => { + return 0; + }); + const words: string[] = ["", ""]; + const item = copy$u8s(rt.bytes(2)); + const grid: Uint8Array[] = Array.from({ length: 2 }, (): Uint8Array => { + return copy$u8s(item); + }); + const item2 = copy$u32s(Array.from({ length: 2 }, (): rt.u32 => { + return 0; + })); + const pairs: rt.u32[][] = Array.from({ length: 2 }, (): rt.u32[] => { + return copy$u32s(item2); + }); + for (const op of rt.byteSliceView(data)) { + const i: rt.usize = op as rt.usize; + const _21: rt.u8 = rt.u8Rem(op, 6); + if (_21 === 0) { + const _23: rt.Place[] = rt.arrayPlaces(rt.byteSliceView(rt.byteSliceFrom(bytes))); + const _25: rt.usize = rt.usizeRem(i, 3); + if (!(_25 < 3)) { + rt.panic("index out of bounds: the len is " + 3 + " but the index is " + _25); + } + _23[_25].v = _23[_25].v ^ op; + const iter2: rt.Iter> = rt.iterSlice(rt.arrayPlaces(rt.byteSliceView(rt.byteSliceFrom(bytes)))); + while (true) { + const _32: rt.Place | rt.Done = iter2.next(); + if (_32 === rt.DONE) { + break; + } + _32.v = rt.u8WrappingAdd(_32.v, 1); + } + } else if (_21 === 1) { + const _40: rt.Place[] = rt.arrayPlaces(wide); + _40[0].v = rt.u16WrappingAdd(_40[0].v, (((op as rt.u16)) << 7) & 0xffff); + const swapped = _40[0].v; + _40[0].v = _40[1].v; + _40[1].v = swapped; + } else if (_21 === 2) { + const _49: rt.Place[] = rt.arrayPlaces(words); + const _51: rt.usize = rt.usizeRem(i, 2); + if (!(_51 < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _51); + } + _49[_51].v = _49[_51].v + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(op, 26)) as rt.char); + } else if (_21 === 3) { + const rows: rt.ByteSlice[] = rt.arrayMap(grid, rt.byteSliceFrom); + const _61: rt.usize = rt.usizeRem(i, 2); + if (!(_61 < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _61); + } + const _64: rt.usize = rt.usizeRem(rt.usizeRem(i, 3), 2); + if (!(_64 < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _64); + } + const slice = rows[_61]; + slice.data[slice.start + _64] = op; + const _71: rt.usize = rt.usizeRem(rt.usizeAdd(i, 1), 2); + if (!(_71 < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _71); + } + rt.byteSliceView(rows[_71]).reverse(); + const _78: rt.u32[][] = rt.arrayFrom(pairs); + const _80: rt.u32 = op as rt.u32; + const _83: rt.usize = rt.usizeRem(i, 2); + if (!(_83 < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _83); + } + _78[0][_83] = (_80 << 20) >>> 0; + rt.sliceCopyFromSlice(_78[1], [_78[0][1], op as rt.u32]); + } else if (_21 === 4) { + rt.arrayPlaces(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.of()))); + const iter3: rt.Iter> = rt.iterSlice([]); + while (true) { + const _99: rt.Place | rt.Done = iter3.next(); + if (_99 === rt.DONE) { + break; + } + _99.v = op; + } + const lens: Uint8Array = rt.bytesMap(rt.arrayFrom(words), (w: string): rt.u8 => { + return rt.stringLen(w) & 0xff; + }); + const rows2: Uint8Array = rt.bytesMap(rt.arrayMap(grid, rt.byteSliceFrom), (row: rt.ByteSlice): rt.u8 => { + return row.data[row.start] ^ row.data[row.start + 1]; + }); + const sums: rt.u32[] = rt.arrayMap(rt.arrayFrom(pairs), (pair: rt.u32[]): rt.u32 => { + return rt.u32WrappingAdd(pair[0], pair[1]); + }); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(lens)); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rows2)); + const _123: rt.usize = rt.usizeRem(i, 2); + if (!(_123 < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _123); + } + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u32ToBeBytes(sums[_123]).reverse())); + } else { + const read: rt.u8[] = rt.arrayFrom(rt.byteSliceView(rt.byteSliceFrom(bytes))); + const wides: rt.u16[] = rt.arrayFrom(wide); + const _135: rt.u8[] = rt.arrayFrom(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.of()))); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(read, f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(wides, f, rt.u16Debug), (f: rt.Formatter) => rt.fmtList(_135, f, rt.u8Debug)]; + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0], " ", args2[1], " ", args2[2]]))); + } + } + [rt.byteSliceFrom(bytes), wide, words, grid, pairs] as [rt.ByteSlice, rt.u16[], string[], Uint8Array[], rt.u32[][]]; + const arg = rt.byteSliceFrom(bytes); + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(arg), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(wide, f, rt.u16Debug), (f: rt.Formatter) => rt.fmtList(words, f, rt.fmtStr), (f: rt.Formatter) => rt.fmtList(grid, f, (value: Uint8Array, f: rt.Formatter) => rt.fmtList(value, f, rt.u8Debug)), (f: rt.Formatter) => rt.fmtList(pairs, f, (value: rt.u32[], f: rt.Formatter) => rt.fmtList(value, f, rt.u32Debug))]; + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args4[0], " ", args4[1], " ", args4[2], " ", args4[3], " ", args4[4]]))); +} + /** * Arrays as slices, of bytes and of other values, empty ones included; each byte an * operation, its value the operand. Writes through `as_mut_slice` land in the array. diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts index 593c49756..d413ff6f7 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -334,6 +334,14 @@ export function map$1diqi3e(self: rt.Place | undefined, f: (a return undefined; } +export function map$1j8xzu6(self: rt.u8 | undefined | rt.None, f: (a0: rt.u8 | undefined) => undefined): undefined | rt.None { + if (self === rt.None) { + return rt.None; + } + f(self); + return undefined; +} + export function map$11y9s7r(self: slices_Pair.Pair[] | undefined, f: (a0: slices_Pair.Pair[]) => rt.u8): rt.u8 | undefined { if (self === undefined) { return undefined; diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 33760dc04..d952555ee 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { fromFns, asSlices } from "./arrays.ts"; +import { fromFns, maps, lent, asSlices } from "./arrays.ts"; import { atomics } from "./atomics.ts"; import { borrows } from "./borrows.ts"; import { bounds } from "./bounds.ts"; @@ -188,7 +188,11 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) uninhabited(data67, out68); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["keys::lent_keys", lentKeys as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["keys::lent_values", lentValues as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["singles::singles", singles as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["singles::formats", singles_formats as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["singles::parses", singles_parses as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["iters::peeked_others", (_2168: rt.u8, data68: rt.ByteSlice, out69: rt.ByteVec): undefined => { peekedOthers(data68, out69); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["hints::hints", hints as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["hints::reserves", reserves as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["collections::set_ops", setOps as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["folds::folds", folds as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["zeros::zeros", zeros as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["hints::hints", hints as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["hints::reserves", reserves as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["collections::set_ops", setOps as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["folds::folds", folds as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["zeros::zeros", zeros as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["arrays::maps", (_2169: rt.u8, data69: rt.ByteSlice, out70: rt.ByteVec): undefined => { + maps(data69, out70); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["arrays::lent", (_2170: rt.u8, data70: rt.ByteSlice, out71: rt.ByteVec): undefined => { + lent(data70, out71); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; } /** Run one case. */ diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts index fee2c63e4..c57a96d5e 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -294,6 +294,10 @@ export function copy$u8s(v: Uint8Array): Uint8Array { return v.slice(); } +export function copy$u8ss(v: Uint8Array[]): Uint8Array[] { + return v.map(copy$u8s); +} + export function copy$units(v: undefined[]): undefined[] { return v.slice(); } diff --git a/ts/fixtures/lang/src/arrays.rs b/ts/fixtures/lang/src/arrays.rs index 6101e2077..2964d0d7d 100644 --- a/ts/fixtures/lang/src/arrays.rs +++ b/ts/fixtures/lang/src/arrays.rs @@ -1,6 +1,7 @@ //! Arrays `array::from_fn` makes, calling its function on each index in order: of bytes, //! wide integers, atomics each its own, strings, nested arrays, none at all, and a length -//! a const parameter gives; and arrays as slices, written through. +//! a const parameter gives; arrays `map` makes; arrays' elements each lent; and arrays as +//! slices, written through. use std::sync::atomic::{AtomicU64, Ordering}; @@ -56,6 +57,128 @@ fn counted(op: u8) -> [usize; N] { std::array::from_fn(|i| i * N + usize::from(op)) } +/// Arrays `map` makes, calling its closure on each element in order; each byte an +/// operation, its value the operand. From bytes and to them, of none at all, through what +/// the closure captured by reference and by move, of `Option`s whose `None` is `rt.None`, +/// and of arrays, each element the closure's own to change. +pub fn maps(data: &[u8], out: &mut Vec) { + for &op in data { + let s = match op % 5 { + 0 => { + let mut seen = Vec::new(); + let bytes = [op, op ^ 1, op ^ 2, op ^ 3]; + let wide: [u16; 4] = bytes.map(|b| { + seen.push(b); + u16::from(b) << 8 | u16::from(op) + }); + let narrow: [u8; 4] = wide.map(|w| (w >> 4) as u8); + let same = narrow.map(|b| b.wrapping_mul(op)); + let words = [u32::from(op), 7, 9].map(|w| w.wrapping_mul(0x0100_0193)); + format!("{bytes:?} {wide:?} {narrow:?} {same:?} {words:?} {seen:?}") + } + 1 => { + let none: [u8; 0] = []; + let wide: [u16; 0] = none.map(u16::from); + let narrow: [u8; 0] = wide.map(|w| w as u8); + let words: [String; 0] = [0u32; 0].map(|n| n.to_string()); + format!("{wide:?} {narrow:?} {words:?}") + } + 2 => { + let word = format!("w{op}"); + let words = [1u8, 2, 3].map(move |i| format!("{word}{i}")); + let shown = format!("{words:?}"); + let lens = words.map(|w| w.len() as u8 + op % 3); + format!("{shown} {lens:?}") + } + 3 => { + let options = [Some(op), None, Some(op.wrapping_add(60))]; + let nested: [Option>; 3] = options.map(|o| o.map(|b| b.checked_add(200))); + let flat = nested.map(|o| match o { + Some(inner) => inner, + None => Some(0), + }); + let units: [Option<()>; 3] = nested.map(|o| o.map(|_| ())); + format!("{options:?} {nested:?} {flat:?} {units:?}") + } + _ => { + let grid = [[op, 1], [2, 3], [4, op]]; + let flipped = grid.map(|mut row| { + row[0] ^= 0xff; + row.reverse(); + row + }); + let sums = flipped.map(|row| u16::from(row[0]) + u16::from(row[1])); + let mut same = grid.map(|row| row); + same[usize::from(op) % 3][0] ^= 0x80; + format!("{grid:?} {flipped:?} {sums:?} {same:?} {:?}", shifted::<3>(op)) + } + }; + out.extend_from_slice(s.as_bytes()); + out.push(b'\n'); + } +} + +/// An array as long as `N` says, mapped by a function. +fn shifted(op: u8) -> [u64; N] { + [op; N].map(u64::from) +} + +/// Arrays' elements lent by `each_ref` and `each_mut`, each byte an operation, its value +/// the operand: bytes, wide integers, and strings, each lent as its place, arrays of bytes +/// as their views, and other arrays as themselves. Writes through each land in the array. +pub fn lent(data: &[u8], out: &mut Vec) { + let mut bytes = [0u8; 3]; + let mut wide = [0u16; 2]; + let mut words = [String::new(), String::new()]; + let mut grid = [[0u8; 2]; 2]; + let mut pairs = [[0u32; 2]; 2]; + let mut none: [u8; 0] = []; + for &op in data { + let i = usize::from(op); + match op % 6 { + 0 => { + *bytes.each_mut()[i % 3] ^= op; + for b in bytes.each_mut() { + *b = b.wrapping_add(1); + } + } + 1 => { + let [first, second] = wide.each_mut(); + *first = first.wrapping_add(u16::from(op) << 7); + std::mem::swap(first, second); + } + 2 => words.each_mut()[i % 2].push(char::from(b'a' + op % 26)), + 3 => { + let rows = grid.each_mut(); + rows[i % 2][i % 3 % 2] = op; + rows[(i + 1) % 2].reverse(); + let [left, right] = pairs.each_mut(); + left[i % 2] = u32::from(op) << 20; + right.copy_from_slice(&[left[1], u32::from(op)]); + } + 4 => { + for b in none.each_mut() { + *b = op; + } + let lens = words.each_ref().map(|w| w.len() as u8); + let rows = grid.each_ref().map(|row| row[0] ^ row[1]); + let sums = pairs.each_ref().map(|pair| pair[0].wrapping_add(pair[1])); + out.extend_from_slice(&lens); + out.extend_from_slice(&rows); + out.extend_from_slice(&sums[i % 2].to_le_bytes()); + } + _ => { + let read: [&u8; 3] = bytes.each_ref(); + let wides: [&u16; 2] = wide.each_ref(); + let s = format!("{read:?} {wides:?} {:?}", none.each_ref()); + out.extend_from_slice(s.as_bytes()); + } + } + } + let s = format!("{bytes:?} {wide:?} {words:?} {grid:?} {pairs:?}"); + out.extend_from_slice(s.as_bytes()); +} + /// Arrays as slices, of bytes and of other values, empty ones included; each byte an /// operation, its value the operand. Writes through `as_mut_slice` land in the array. pub fn as_slices(data: &[u8], out: &mut Vec) { diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 535e5205d..7bc600cb7 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -167,6 +167,8 @@ fn cases() -> Vec<(&'static str, Case)> { ("collections::set_ops", collections::set_ops), ("folds::folds", folds::folds), ("zeros::zeros", zeros::zeros), + ("arrays::maps", |_, data, out| arrays::maps(data, out)), + ("arrays::lent", |_, data, out| arrays::lent(data, out)), ] } diff --git a/ts/fixtures/lang/src/lib.rs b/ts/fixtures/lang/src/lib.rs index 051824da1..d20030584 100644 --- a/ts/fixtures/lang/src/lib.rs +++ b/ts/fixtures/lang/src/lib.rs @@ -7,8 +7,9 @@ //! and `Result`'s combinators from core's MIR, `Option`s of values that can already be //! `undefined`, atomics, `static` ones included, trait objects, one-time cells, mutexes, //! `Cell`s, `UnsafeCell`s, `RefCell`s, read-write locks, and thread-locals, the defaults -//! of std types, the counts of shared pointers, arrays `array::from_fn` makes, arrays as -//! slices, maps of `Option`s, values held back past a write of a variable they name, what +//! of std types, the counts of shared pointers, arrays `array::from_fn` and `map` make, +//! their elements each lent, arrays as slices, maps of `Option`s, values held back past a +//! write of a variable they name, what //! `Hash` writes into `DefaultHasher` and `RandomState`, slices' `windows` and chunks, //! mutable ones written through, their parts by inclusive and checked ranges and by fixed //! size, `Vec::drain`, the order, equality, and hashes of bytes, ranges of `Bound`s and of diff --git a/ts/fixtures/task/expected/drops/closures.ts b/ts/fixtures/task/expected/drops/closures.ts index 0cd4d6061..3c1383427 100644 --- a/ts/fixtures/task/expected/drops/closures.ts +++ b/ts/fixtures/task/expected/drops/closures.ts @@ -1,8 +1,8 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; -import { thenSome$1af3oea, then$1xpp3sz, then$1j9nint, then$0kxuq3f } from "../core/bool.ts"; -import { map$1raha9y, map$0b0x7xy, map$1thjygq, mapOr$0nrpycp } from "../core/option.ts"; +import { thenSome$0zvoczk, thenSome$1af3oea, then$1xpp3sz, then$1j9nint, then$0kxuq3f } from "../core/bool.ts"; +import { map$1raha9y, map$0lq7mno, map$0b0x7xy, map$1thjygq, mapOr$0nrpycp } from "../core/option.ts"; import { map$1rk4yqp, mapErr$1c43xsx, inspectErr$0hrcm18, andThen$1so3lx6 } from "../core/result.ts"; import * as Holder from "../drops/closures.Holder.ts"; import * as Log from "../log.Log.ts"; @@ -443,8 +443,8 @@ export function iterated(log: Log.Log, id: rt.u32): void { const chained: rt.Iter = rt.iterInspect(_106, rt.closure((g7: Guard.Guard): undefined => { const _92: rt.u32 = Guard.id(g7); const _11: rt.u32 = Guard.id(captured5); - const args28: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(_92, f), (f: rt.Formatter) => rt.u32Display(_11, f)]; - Log.note(log, rt.fmtFormat(["inspect ", args28[0], " ", args28[1]])); + const args30: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(_92, f), (f: rt.Formatter) => rt.u32Display(_11, f)]; + Log.note(log, rt.fmtFormat(["inspect ", args30[0], " ", args30[1]])); }, (): void => { captured5[Symbol.dispose](); })); @@ -608,8 +608,8 @@ export function iterated(log: Log.Log, id: rt.u32): void { const captured17 = o; const _372: (a0: rt.u32) => undefined = rt.closure((_214: rt.u32): undefined => { const part7 = rt.u32Add(_214, Guard.id(captured17)); - const args30: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part7, f)]; - Log.note(log, rt.fmtFormat(["each ", args30[0]])); + const args32: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part7, f)]; + Log.note(log, rt.fmtFormat(["each ", args32[0]])); }, (): void => { captured17[Symbol.dispose](); }); @@ -695,6 +695,24 @@ export function iterated(log: Log.Log, id: rt.u32): void { const _502: rt.usize = queue.n; const args26: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_499, f), (f: rt.Formatter) => rt.usizeDisplay(_502, f)]; Log.note(log, rt.fmtFormat(["retained ", args26[0], " ", args26[1]])); + const x: Guard.Guard = guard(48); + const _513: Guard.Guard[] = [guard(49), guard(50), guard(51)]; + const captured25 = x; + const _523: (a0: Guard.Guard) => Guard.Guard | undefined = rt.closure((g20: Guard.Guard): Guard.Guard | undefined => { + const part10 = Guard.id(g20); + const args34: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part10, f)]; + Log.note(log, rt.fmtFormat(["array map ", args34[0]])); + return thenSome$0zvoczk(Guard.id(g20) !== rt.u32Add(Guard.id(captured25), 2), g20); + }, (): void => { + captured25[Symbol.dispose](); + }); + const kept: Array = rt.dropAfter(_523, () => rt.arrayMap(_513, _523)); + const part11 = rt.arrayMap(rt.arrayFrom(kept), (g21: Guard.Guard | undefined): rt.u32 | undefined => { + return map$0lq7mno(g21, Guard.id); + }); + const args28: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(part11, f, (value: rt.u32 | undefined, f: rt.Formatter) => rt.fmtOption(value, f, rt.u32Debug))]; + Log.note(log, rt.fmtFormat(["array mapped ", args28[0]])); + rt.dropAll(kept); rt.dequeDrop(queue, rt.drop); rt.btreeDrop(map, undefined, rt.drop); rt.dropAll(items); diff --git a/ts/fixtures/task/src/drops/closures.rs b/ts/fixtures/task/src/drops/closures.rs index a666ee100..1f654d203 100644 --- a/ts/fixtures/task/src/drops/closures.rs +++ b/ts/fixtures/task/src/drops/closures.rs @@ -231,4 +231,15 @@ pub(super) fn iterated(log: &Log, id: u32) { let q = guard(35); queue.retain(move |g| g.id() + 2 != q.id()); log.note(format!("retained {} {}", map.len(), queue.len())); + // An array's `map` moves each element into its closure, which drops after the last call, + // and its result holds what the closure kept until it drops. + let x = guard(48); + let kept = [guard(49), guard(50), guard(51)].map(move |g| { + log.note(format!("array map {}", g.id())); + (g.id() != x.id() + 2).then_some(g) + }); + log.note(format!( + "array mapped {:?}", + kept.each_ref().map(|g| g.as_ref().map(Guard::id)) + )); } diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index 6a5251d98..6e2aa80cd 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -986,6 +986,32 @@ export function bytesFromFn(n: number, f: (i: number) => number): Uint8Array { return out; } +/** `<[T; N]>::map`: `f` of each element, called in order. */ +export function arrayMap(a: ArrayLike, f: (x: T) => U): U[] { + const out: U[] = []; + for (let i = 0; i < a.length; i++) out.push(f(a[i])); + return out; +} + +/** `<[T; N]>::map` to bytes. */ +export function bytesMap(a: ArrayLike, f: (x: T) => number): Uint8Array { + const out = bytes(a.length); + for (let i = 0; i < a.length; i++) out[i] = f(a[i]); + return out; +} + +/** `<[T; N]>::each_ref` and `each_mut` of elements lent as themselves. */ +export function arrayFrom(a: ArrayLike): T[] { + return Array.from(a); +} + +/** `<[T; N]>::each_mut` of elements JS copies: the place of each. */ +export function arrayPlaces(a: { [i: number]: T; length: number }): Place[] { + const out: Place[] = []; + for (let i = 0; i < a.length; i++) out.push(new AtIndex(a, i)); + return out; +} + /** `Vec`: a growable byte buffer. */ export class ByteVec { /** The storage; only the first `length` bytes are the vector. */ diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 2c4749cb2..623e20080 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -719,7 +719,9 @@ fn discards(owner: &str, name: &str) -> Option<&'static [usize]> { | ("Into", "into") // What a panic would drop, which aborts. | ("Result", "unwrap" | "expect" | "unwrap_err") - | ("Vec", "insert") => &[], + | ("Vec", "insert") + // Each element moves into the closure. + | ("array", "map") => &[], // `Vec` drops each element `retain` rejects, `dedup` removes, and `truncate` and // `clear` cut. ("Vec", "retain" | "retain_mut" | "dedup" | "dedup_by" | "dedup_by_key" | "truncate" | "clear") => &[0], @@ -875,8 +877,8 @@ pub fn called_through<'tcx>( /// The closures `call` calls that own a value that drops, by what its mapping does with /// each: kept by the iterator it returns, if `iter::holds_closure`; dropped as it returns, if -/// `Fn` or `FnMut` call it and nothing else it takes by value drops, as then nothing it -/// drops is ordered against it; dropped where `discarded` says, by the type's index among +/// `Fn` or `FnMut` call it and nothing else it takes by value drops, or the mapping discards +/// none of it, as then nothing it drops is ordered against it; dropped where `discarded` says, by the type's index among /// the call's type arguments; or else leaked. A closure that `Fn` or `FnMut` call, given to /// one that calls it through `FnOnce`, becomes `rt.once` of it, which drops it after the /// call, as rustc's shim does. A reference to one is the closure in JS, so an iterator, @@ -939,7 +941,11 @@ fn called_closures<'tcx>( let discards = discarded.is_some_and(|d| d.contains(&index)); let kept = inputs.iter().enumerate().any(|(j, &t)| j != i && mentions(t)); if bound != ty::ClosureKind::FnOnce && !kept && !discards && i < args.len() { - match dropping_operand(b, call) { + let dropping = match discarded { + Some([]) => None, + _ => dropping_operand(b, call), + }; + match dropping { None => closures.spent.push(args[i].clone()), Some(_) => closures.leaked = closures.leaked.or(Some(ty)), } @@ -1935,6 +1941,24 @@ fn mapping<'tcx>( }; Expr::rt(f, vec![Expr::lit(n.to_string()), args.pop()?]) } + ("array", "map") => { + let f = match targ(gargs, 2).kind() { + ty::Uint(ty::UintTy::U8) => "bytesMap", + _ => "arrayMap", + }; + Expr::rt(f, args) + } + // Each element lent as `first_mut` lends it: an element JS copies as its place, an + // array of bytes as its view, and an object as itself. + ("array", "each_ref" | "each_mut") => { + let elem = targ(gargs, 0); + let a = elements(args.pop()?, Ty::new_slice(tcx, elem)); + match () { + _ if name == "each_mut" && b.t.needs_place(elem) => Expr::rt("arrayPlaces", vec![a]), + _ if super::byte_array(elem) => Expr::rt("arrayMap", vec![a, Expr::Rt("byteSliceFrom".into())]), + _ => Expr::rt("arrayFrom", vec![a]), + } + } ("fmt", "format") => { let parts = args.pop()?; match literal(&parts) { diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 552cbee5c..420de4ee0 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -175,7 +175,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { ("Index" | "IndexMut", "index" | "index_mut") | ("Clone", "clone") | ("Argument", _) => true, // The runtime compares and hashes bytes in whichever form it is given them. ("PartialOrd" | "Ord" | "PartialEq", _) | ("Hash", "hash") => true, - ("slice", "iter" | "iter_mut") => true, + ("slice", "iter" | "iter_mut") | ("array", "each_ref" | "each_mut") => true, ("IntoIterator", "into_iter") => self_ty.is_some_and(|s| elem(tcx, s).is_some()), _ => false, }; @@ -385,6 +385,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let lends = match library::key(tcx, def_id) { Some((owner, name)) => match (owner.as_str(), name.as_str()) { ("slice", "get_mut" | "first_mut" | "last_mut" | "iter_mut" | "split_first_mut" | "split_last_mut") + | ("array", "each_mut") | ("dyn Any", "downcast_mut") | ("Peekable", "peek_mut") | ("LocalKey", "with_borrow_mut")