From 81b7cab1694615b741550335541a452f706b4c48 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:42:38 -0700 Subject: [PATCH 01/15] chore(quest): claim quest/m2/ts-mir-size.md Quest-Claim: 4f881bb5b70f75e4 From a1814b2229b03023350b913e671df75aa1557f0c Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:02:50 -0700 Subject: [PATCH 02/15] feat(ts): fold single-use temporaries and loop over arrays with for-of Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/codec/expected/bench.ts | 17 +- .../codec/expected/coding/decode.Decoder.ts | 10 +- .../codec/expected/coding/encode.Encoder.ts | 26 +- ts/fixtures/codec/expected/coding/varint.ts | 18 +- .../codec/expected/coding/version.Versions.ts | 26 +- ts/fixtures/codec/expected/harness.ts | 55 +-- .../codec/expected/lite/group.Group.ts | 4 +- ts/fixtures/codec/expected/lite/message.ts | 6 +- .../codec/expected/lite/probe.Probe.ts | 4 +- ts/fixtures/lang/expected/chars.ts | 36 +- ts/fixtures/lang/expected/collections.ts | 149 ++----- ts/fixtures/lang/expected/fmt.Fails.ts | 3 +- ts/fixtures/lang/expected/fmt.Manual.ts | 3 +- ts/fixtures/lang/expected/fmt.Nested.ts | 3 +- ts/fixtures/lang/expected/fmt.Six.ts | 3 +- ts/fixtures/lang/expected/fmt.Tup.ts | 6 +- ts/fixtures/lang/expected/fmt.Wide.ts | 3 +- ts/fixtures/lang/expected/fmt.ts | 21 +- ts/fixtures/lang/expected/ints.ts | 380 ++++++------------ ts/fixtures/lang/expected/iters.ts | 93 ++--- ts/fixtures/lang/expected/keys.ts | 27 +- ts/fixtures/lang/expected/shapes.Shape.ts | 4 +- ts/fixtures/lang/expected/shapes.ts | 190 ++------- ts/fixtures/task/expected/kio.Consumer.ts | 4 +- ts/fixtures/task/expected/kio.Producer.ts | 9 +- ts/fixtures/task/expected/kio.Waiter.ts | 3 +- ts/fixtures/task/expected/kio.WaiterList.ts | 37 +- ts/fixtures/task/expected/log.Log.ts | 4 +- ts/fixtures/task/expected/model.ts | 18 +- ts/src/lower/mir/cfg.rs | 33 +- ts/src/lower/mir/inline.rs | 166 ++++++++ ts/src/lower/mir/mod.rs | 93 ++++- ts/src/lower/mir/step.rs | 191 +++++++++ ts/src/print.rs | 24 +- ts/src/ts.rs | 9 +- 35 files changed, 798 insertions(+), 880 deletions(-) create mode 100644 ts/src/lower/mir/inline.rs diff --git a/ts/fixtures/codec/expected/bench.ts b/ts/fixtures/codec/expected/bench.ts index 76cd49842..0d9e5acd4 100644 --- a/ts/fixtures/codec/expected/bench.ts +++ b/ts/fixtures/codec/expected/bench.ts @@ -202,8 +202,7 @@ export function decodeSplit(data: Uint8Array, version: Version.Version, out: rt. if (!(start < end)) { continue l2; } - const slice = _6[1]; - const r: Decoder.Decoder = Decoder.new(rt.sliceRange(slice, start, end), Form.from$From_Version(version)); + const r: Decoder.Decoder = Decoder.new(rt.sliceRange(_6[1], start, end), Form.from$From_Version(version)); const _32: rt.Result<[rt.i64, rt.u64], DecodeError.DecodeError> = frameHeader(r); if (_32.ok) { const delta: rt.i64 = _32.value[0]; @@ -217,8 +216,7 @@ export function decodeSplit(data: Uint8Array, version: Version.Version, out: rt. short = rt.usizeAdd(short, 1); continue l2; } - const _0: rt.Result = rt.Err(_32.error); - return _0; + return rt.Err(_32.error); } } } @@ -250,8 +248,7 @@ export function frameHeader(r: Decoder.Decoder): rt.Result<[rt.i64, rt.u64], Dec export function encodeGroup(data: Uint8Array, version: Version.Version, out: rt.ByteVec): rt.Result { const _6: [rt.u64, Uint8Array] = takeU64(data); const group: Group.Group = { subscribe: _6[0], sequence: takeU64(_6[1])[0], frameStart: 0 }; - const _12: Encoder.Encoder = Encoder.new(out, Form.from$From_Version(version)); - return Group.encode$Encode_Version(group, _12, version); + return Group.encode$Encode_Version(group, Encoder.new(out, Form.from$From_Version(version)), version); } /** @@ -279,10 +276,7 @@ export function ordered(data: Uint8Array, out: rt.ByteVec): void { let iterStart2: rt.u32 = 0; const iterEnd2: rt.u32 = count2; while ((_28 = iterStart2++) < iterEnd2) { - const i2: rt.u32 = _28; - const _42: rt.u32 = rt.u32Sub(count2, 1); - const part = rt.u32Sub(_42, i2); - const _38: rt.u32 = _10(part); + const _38: rt.u32 = _10(rt.u32Sub(rt.u32Sub(count2, 1), _28)); sum = rt.u64Add(sum, rt.optionUnwrapOr(rt.btreeGet(map, _38), 0) as rt.u64); } const _49: rt.Range = new rt.Range(1 << 14, 2 << 14); @@ -315,8 +309,7 @@ export function iterate(chain: rt.u8, data: Uint8Array, out: rt.ByteVec): void { return (_212 & 1) === 0; }))); } else if (chain === 1) { - const _11: rt.Iter = rt.iterSlice(data); - rt.byteVecPush(out, rt.iterAny(_11, (_210: rt.u8): boolean => { + rt.byteVecPush(out, rt.iterAny(rt.iterSlice(data), (_210: rt.u8): boolean => { return _210 === 255; }) ? 1 : 0); } else if (chain === 2) { diff --git a/ts/fixtures/codec/expected/coding/decode.Decoder.ts b/ts/fixtures/codec/expected/coding/decode.Decoder.ts index 5e25955be..175b81bab 100644 --- a/ts/fixtures/codec/expected/coding/decode.Decoder.ts +++ b/ts/fixtures/codec/expected/coding/decode.Decoder.ts @@ -46,8 +46,7 @@ export function need(self: Decoder): rt.usize { /** Record that a read wanted `more` bytes past the current position. */ export function short(self: Decoder, more: rt.usize): DecodeError.DecodeError { const need_: rt.usize = rt.usizeSaturatingAdd(rt.usizeSub(self.len, self.buf.length), more); - const _9: rt.usize = self.need; - self.need = rt.max(_9, need_); + self.need = rt.max(self.need, need_); return { tag: "Short" } as DecodeError.DecodeError; } @@ -128,9 +127,7 @@ export function bool(self: Decoder): rt.Result /** Read a varint. */ export function varint(self: Decoder): rt.Result { let _0!: rt.Result; - const _13: Uint8Array = self.buf; - const _3: Form.Form = copy$Form(self.form); - const _2: rt.Result<[rt.u64, Uint8Array], DecodeError.DecodeError> = read(_13, _3); + const _2: rt.Result<[rt.u64, Uint8Array], DecodeError.DecodeError> = read(self.buf, copy$Form(self.form)); if (_2.ok) { const value: rt.u64 = _2.value[0]; self.buf = _2.value[1]; @@ -178,8 +175,7 @@ export function string(self: Decoder): rt.Result = _2; - return rt.Err(DecodeError.from$From_FromUtf8Error((residual2 as { ok: false; error: rt.FromUtf8Error }).error)); + return rt.Err(DecodeError.from$From_FromUtf8Error((_2 as { ok: false; error: rt.FromUtf8Error }).error)); } return _5; } diff --git a/ts/fixtures/codec/expected/coding/encode.Encoder.ts b/ts/fixtures/codec/expected/coding/encode.Encoder.ts index 553371c0f..29ba6d30e 100644 --- a/ts/fixtures/codec/expected/coding/encode.Encoder.ts +++ b/ts/fixtures/codec/expected/coding/encode.Encoder.ts @@ -5,7 +5,6 @@ import * as EncodeError from "../coding/encode.EncodeError.ts"; import type * as Prefix from "../coding/encode.Prefix.ts"; import type * as PrefixKind from "../coding/encode.PrefixKind.ts"; import { write } from "../coding/varint.ts"; -import type * as BoundsExceeded from "../coding/varint.BoundsExceeded.ts"; import type * as Form from "../coding/varint.Form.ts"; import type * as Control from "../stats.Control.ts"; @@ -47,8 +46,7 @@ export function bool(self: Encoder, v: boolean): void { /** Write a varint, or fail with [`EncodeError::BoundsExceeded`] if the form cannot carry it. */ export function varint(self: Encoder, v: rt.u64): rt.Result { - const _3: rt.Result = write(v, self.form, self.buf); - if (_3.ok) { + if (write(v, self.form, self.buf).ok) { return rt.Ok(undefined); } return rt.Err(EncodeError.from$From_BoundsExceeded({})); @@ -122,32 +120,25 @@ export function fill(self: Encoder, prefix: Prefix.Prefix): rt.Result = write(rt.usizeSub(end, body) as rt.u64, self.form, self.buf); - if (_23.ok) { + if (write(rt.usizeSub(end, body) as rt.u64, self.form, self.buf).ok) { const len: rt.usize = rt.usizeSub(self.buf.length, end); if (!(len === 1)) { const size2: Uint8Array = rt.bytes(9); - const _44: Uint8Array = rt.sliceRange(size2, 0, len); - const slice4 = rt.byteVecView(self.buf); - rt.sliceCopyFromSlice(_44, rt.sliceRange(slice4, end)); + rt.sliceCopyFromSlice(rt.sliceRange(size2, 0, len), rt.sliceRange(rt.byteVecView(self.buf), end)); rt.byteVecTruncate(self.buf, rt.usizeSub(rt.usizeAdd(end, len), 1)); const _58: rt.usize = rt.usizeSub(rt.usizeAdd(body, len), 1); - const _56: Uint8Array = rt.byteVecView(self.buf); - rt.sliceCopyWithin(_56, body, end, _58); + rt.sliceCopyWithin(rt.byteVecView(self.buf), body, end, _58); const _84: rt.ByteVec = self.buf; const part2 = rt.usizeSub(body, 1); const part3 = rt.usizeAdd(rt.usizeSub(body, 1), len); - const slice5 = rt.byteVecView(_84); - rt.sliceCopyFromSlice(rt.sliceRange(slice5, part2, part3), rt.sliceRange(size2, 0, len)); + rt.sliceCopyFromSlice(rt.sliceRange(rt.byteVecView(_84), part2, part3), rt.sliceRange(size2, 0, len)); } else { const slice2 = rt.byteVecView(self.buf); - const at = rt.idx(slice2, end); - const _35: rt.u8 = slice2[at]; + const _35: rt.u8 = slice2[rt.idx(slice2, end)]; const _79: rt.ByteVec = self.buf; const _39: rt.usize = rt.usizeSub(body, 1); const slice3 = rt.byteVecView(_79); - const at2 = rt.idx(slice3, _39); - slice3[at2] = _35; + slice3[rt.idx(slice3, _39)] = _35; rt.byteVecTruncate(self.buf, end); return rt.Ok(undefined); } @@ -162,8 +153,7 @@ export function fill(self: Encoder, prefix: Prefix.Prefix): rt.Result = rt.optionOkOr(rt.sliceSplitFirstChunk(buf, 8), { tag: "Short" } as DecodeError.DecodeError); if (_54.ok) { const val3: [Uint8Array, Uint8Array] = _54.value; - const slice = val3[0]; - return rt.Ok([fromHalves((((val3[0][0] & 63) << 24) | (val3[0][1] << 16) | (val3[0][2] << 8) | val3[0][3]) >>> 0, rt.u32FromBeBytes(slice.subarray(4, 8))), val3[1]] as [rt.u64, Uint8Array]); + return rt.Ok([fromHalves((((val3[0][0] & 63) << 24) | (val3[0][1] << 16) | (val3[0][2] << 8) | val3[0][3]) >>> 0, rt.u32FromBeBytes(val3[0].subarray(4, 8))), val3[1]] as [rt.u64, Uint8Array]); } return _54; } @@ -268,8 +267,7 @@ export function readLeadingOnes(buf: Uint8Array, seven: boolean): rt.Result<[rt. const _65: rt.Result<[Uint8Array, Uint8Array], DecodeError.DecodeError> = rt.optionOkOr(rt.sliceSplitFirstChunk(buf, 5), { tag: "Short" } as DecodeError.DecodeError); if (_65.ok) { const val4: [Uint8Array, Uint8Array] = _65.value; - const slice5 = val4[0]; - _8 = [fromHalves(((val4[0][0] & 7)) as rt.u32, rt.u32FromBeBytes(slice5.subarray(1, 5))), val4[1]] as [rt.u64, Uint8Array]; + _8 = [fromHalves(((val4[0][0] & 7)) as rt.u32, rt.u32FromBeBytes(val4[0].subarray(1, 5))), val4[1]] as [rt.u64, Uint8Array]; } else { return _65; } @@ -277,8 +275,7 @@ export function readLeadingOnes(buf: Uint8Array, seven: boolean): rt.Result<[rt. const _81: rt.Result<[Uint8Array, Uint8Array], DecodeError.DecodeError> = rt.optionOkOr(rt.sliceSplitFirstChunk(buf, 6), { tag: "Short" } as DecodeError.DecodeError); if (_81.ok) { const val5: [Uint8Array, Uint8Array] = _81.value; - const slice4 = val5[0]; - _8 = [fromHalves(((val5[0][0] & 3) << 8) | val5[0][1], rt.u32FromBeBytes(slice4.subarray(2, 6))), val5[1]] as [rt.u64, Uint8Array]; + _8 = [fromHalves(((val5[0][0] & 3) << 8) | val5[0][1], rt.u32FromBeBytes(val5[0].subarray(2, 6))), val5[1]] as [rt.u64, Uint8Array]; } else { return _81; } @@ -289,8 +286,7 @@ export function readLeadingOnes(buf: Uint8Array, seven: boolean): rt.Result<[rt. const _101: rt.Result<[Uint8Array, Uint8Array], DecodeError.DecodeError> = rt.optionOkOr(rt.sliceSplitFirstChunk(buf, 7), { tag: "Short" } as DecodeError.DecodeError); if (_101.ok) { const val6: [Uint8Array, Uint8Array] = _101.value; - const slice3 = val6[0]; - _8 = [fromHalves(((val6[0][0] & 1) << 16) | (val6[0][1] << 8) | val6[0][2], rt.u32FromBeBytes(slice3.subarray(3, 7))), val6[1]] as [rt.u64, Uint8Array]; + _8 = [fromHalves(((val6[0][0] & 1) << 16) | (val6[0][1] << 8) | val6[0][2], rt.u32FromBeBytes(val6[0].subarray(3, 7))), val6[1]] as [rt.u64, Uint8Array]; } else { return _101; } @@ -298,8 +294,7 @@ export function readLeadingOnes(buf: Uint8Array, seven: boolean): rt.Result<[rt. const _121: rt.Result<[Uint8Array, Uint8Array], DecodeError.DecodeError> = rt.optionOkOr(rt.sliceSplitFirstChunk(buf, 8), { tag: "Short" } as DecodeError.DecodeError); if (_121.ok) { const val7: [Uint8Array, Uint8Array] = _121.value; - const slice2 = val7[0]; - _8 = [fromHalves((val7[0][1] << 16) | (val7[0][2] << 8) | val7[0][3], rt.u32FromBeBytes(slice2.subarray(4, 8))), val7[1]] as [rt.u64, Uint8Array]; + _8 = [fromHalves((val7[0][1] << 16) | (val7[0][2] << 8) | val7[0][3], rt.u32FromBeBytes(val7[0].subarray(4, 8))), val7[1]] as [rt.u64, Uint8Array]; } else { return _121; } @@ -307,8 +302,7 @@ export function readLeadingOnes(buf: Uint8Array, seven: boolean): rt.Result<[rt. const _142: rt.Result<[Uint8Array, Uint8Array], DecodeError.DecodeError> = rt.optionOkOr(rt.sliceSplitFirstChunk(buf, 9), { tag: "Short" } as DecodeError.DecodeError); if (_142.ok) { const val8: [Uint8Array, Uint8Array] = _142.value; - const slice = val8[0]; - _8 = [fromHalves(rt.u32FromBeBytes(slice.subarray(1, 5)), ((val8[0][5] << 24) | (val8[0][6] << 16) | (val8[0][7] << 8) | val8[0][8]) >>> 0), val8[1]] as [rt.u64, Uint8Array]; + _8 = [fromHalves(rt.u32FromBeBytes(val8[0].subarray(1, 5)), ((val8[0][5] << 24) | (val8[0][6] << 16) | (val8[0][7] << 8) | val8[0][8]) >>> 0), val8[1]] as [rt.u64, Uint8Array]; } else { return _142; } diff --git a/ts/fixtures/codec/expected/coding/version.Versions.ts b/ts/fixtures/codec/expected/coding/version.Versions.ts index 518b5aa6e..f1a961f65 100644 --- a/ts/fixtures/codec/expected/coding/version.Versions.ts +++ b/ts/fixtures/codec/expected/coding/version.Versions.ts @@ -15,9 +15,7 @@ export function decodeSlice$Decode_Form(buf: Uint8Array, version: Form.Form): rt const r: Decoder.Decoder = Decoder.new(buf, version); const _6: rt.Result = decode$Decode_Form(r, version); if (_6.ok) { - const val: Versions = _6.value; - const _0: rt.Result<[Versions, rt.usize], DecodeError.DecodeError> = rt.Ok([val, rt.usizeSub(buf.length, Decoder.remaining(r))]); - return _0; + return rt.Ok([_6.value, rt.usizeSub(buf.length, Decoder.remaining(r))]); } return _6; } @@ -34,11 +32,7 @@ export function decode$Decode_Form(r: Decoder.Decoder, version: Form.Form): rt.R const count: rt.u64 = _3.value; const vs: Version.Version[] = []; const iter: rt.Range = new rt.Range(0, count, rt.u64Step); - while (true) { - const _12: rt.u64 | rt.Done = iter.next(); - if (_12 === rt.DONE) { - break; - } + while (iter.next() !== rt.DONE) { const _15: rt.Result = Version.decode$Decode_Form(r, version); if (_15.ok) { vs.push(_15.value); @@ -55,13 +49,7 @@ export function decode$Decode_Form(r: Decoder.Decoder, version: Form.Form): rt.R export function encode$Encode_Form(self: Versions, w: Encoder.Encoder, version: Form.Form): rt.Result { const _4: rt.Result = Encoder.varint(w, self._0.length as rt.u64); if (_4.ok) { - const iterS: Version.Version[] = self._0; - let iterI: number = 0; - while (true) { - const _14: Version.Version | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_14 === rt.DONE) { - break; - } + for (const _14 of self._0) { const _18: rt.Result = Version.encode$Encode_Form(_14, w, version); if (!_18.ok) { return _18; @@ -76,13 +64,7 @@ export function encode$Encode_Form(self: Versions, w: Encoder.Encoder, version: export function encode$Encode_Version(self: Versions, w: Encoder.Encoder, version: version_Version.Version): rt.Result { const _4: rt.Result = Encoder.varint(w, self._0.length as rt.u64); if (_4.ok) { - const iterS: Version.Version[] = self._0; - let iterI: number = 0; - while (true) { - const _14: Version.Version | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_14 === rt.DONE) { - break; - } + for (const _14 of self._0) { const _18: rt.Result = Version.encode$Encode_Version(_14, w, version); if (!_18.ok) { return _18; diff --git a/ts/fixtures/codec/expected/harness.ts b/ts/fixtures/codec/expected/harness.ts index 5d91d1f77..1efea3b26 100644 --- a/ts/fixtures/codec/expected/harness.ts +++ b/ts/fixtures/codec/expected/harness.ts @@ -101,8 +101,7 @@ export function decodeFailed(out: rt.ByteVec, err: DecodeError.DecodeError): voi const _5: string = rt.fmtToString((f: rt.Formatter) => DecodeError.fmt$Display(err, f)); const arg = ([err] as [DecodeError.DecodeError])[0]; const args2: rt.Fmt[] = [(f: rt.Formatter) => DecodeError.fmt$Debug(arg, f)]; - const _6: string = rt.fmtFormat([args2[0]]); - putText(out, _5, _6); + putText(out, _5, rt.fmtFormat([args2[0]])); } /** An encode error's code, then its text. */ @@ -111,8 +110,7 @@ export function encodeFailed(out: rt.ByteVec, err: EncodeError.EncodeError): voi const _5: string = rt.fmtToString((f: rt.Formatter) => EncodeError.fmt$Display(err, f)); const arg = ([err] as [EncodeError.EncodeError])[0]; const args2: rt.Fmt[] = [(f: rt.Formatter) => EncodeError.fmt$Debug(arg, f)]; - const _6: string = rt.fmtFormat([args2[0]]); - putText(out, _5, _6); + putText(out, _5, rt.fmtFormat([args2[0]])); } /** An error's thiserror `Display` and derived `Debug`, which callers see. */ @@ -200,17 +198,9 @@ export function decodeScript(data: Uint8Array, out: rt.ByteVec): void { const selector: rt.u8 = _5[0]; const _9: [rt.u8, Uint8Array] | undefined = rt.sliceSplitFirst(_5[1]); if (_9 !== undefined) { - const len: rt.u8 = _9[0]; - const _15: rt.usize = _9[1].length; - const _13: [Uint8Array, Uint8Array] = rt.sliceSplitAt(_9[1], rt.min(_15, len as rt.usize)); + const _13: [Uint8Array, Uint8Array] = rt.sliceSplitAt(_9[1], rt.min(_9[1].length, _9[0] as rt.usize)); const r: Decoder.Decoder = Decoder.new(_13[1], form(selector)); - const iterS: Uint8Array = _13[0]; - let iterI: number = 0; - while (true) { - const _21: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_21 === rt.DONE) { - break; - } + for (const _21 of _13[0]) { const _26: rt.Result = decodeStep(r, _21, out); if (_26.ok) { rt.byteVecPush(out, 0); @@ -322,22 +312,13 @@ export function encodeScript(data: Uint8Array, out: rt.ByteVec): void { const selector: rt.u8 = _5[0]; const _9: [rt.u8, Uint8Array] | undefined = rt.sliceSplitFirst(_5[1]); if (_9 !== undefined) { - const len: rt.u8 = _9[0]; - const _15: rt.usize = _9[1].length; - const _13: [Uint8Array, Uint8Array] = rt.sliceSplitAt(_9[1], rt.min(_15, len as rt.usize)); + const _13: [Uint8Array, Uint8Array] = rt.sliceSplitAt(_9[1], rt.min(_9[1].length, _9[0] as rt.usize)); let values: Uint8Array = _13[1]; const buf: rt.ByteVec = new rt.ByteVec(); const _20: Form.Form = form(selector); const w: Encoder.Encoder = Encoder.new(buf, _20); const prefixes: Prefix.Prefix[] = []; - const iterS: Uint8Array = _13[0]; - let iterI: number = 0; - while (true) { - const _24: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_24 === rt.DONE) { - break; - } - const step: rt.u8 = _24; + for (const step of _13[0]) { const _30: [rt.u64, Uint8Array] = takeU64(values); const value: rt.u64 = _30[0]; values = _30[1]; @@ -365,14 +346,12 @@ export function encodeScript(data: Uint8Array, out: rt.ByteVec): void { result = Encoder.varintOpt(w, _47); } else if (_33 === 5) { const part = rt.u8Rem(rt.u8Div(step, 10), 9) as rt.usize; - const _53: Uint8Array = rt.u64ToBeBytes(value); - const _51: Uint8Array = rt.sliceRange(_53, 0, part); + const _51: Uint8Array = rt.sliceRange(rt.u64ToBeBytes(value), 0, part); result = Encoder.bytes(w, _51); } else if (_33 === 6) { const _60: rt.Result = rt.stringFromUtf8(rt.sliceToByteVec(rt.u64ToBeBytes(value))); if (_60.ok) { - const _68: string = _60.value; - result = Encoder.string(w, _68); + result = Encoder.string(w, _60.value); } else { result = Encoder.string(w, "not utf-8"); } @@ -454,8 +433,7 @@ export function roundtrip$Versions(data: Uint8Array, out: rt.ByteVec): void { const value: Versions.Versions = _8.value[0]; putUsize(out, _8.value[1]); const buf: rt.ByteVec = new rt.ByteVec(); - const _17: Encoder.Encoder = Encoder.new(buf, form_); - const _14: rt.Result = Versions.encode$Encode_Form(value, _17, form_); + const _14: rt.Result = Versions.encode$Encode_Form(value, Encoder.new(buf, form_), form_); if (_14.ok) { rt.byteVecExtendFromSlice(out, rt.byteVecView(buf)); } else { @@ -478,8 +456,7 @@ export function roundtripLite$Group(data: Uint8Array, out: rt.ByteVec): void { putUsize(out, _8.value[1]); const buf: rt.ByteVec = new rt.ByteVec(); const _19: Form.Form = Form.from$From_Version(version); - const _17: Encoder.Encoder = Encoder.new(buf, _19); - const _14: rt.Result = Group.encode$Encode_Version(value, _17, version); + const _14: rt.Result = Group.encode$Encode_Version(value, Encoder.new(buf, _19), version); if (_14.ok) { rt.byteVecExtendFromSlice(out, rt.byteVecView(buf)); } else { @@ -502,8 +479,7 @@ export function roundtripLite$Probe(data: Uint8Array, out: rt.ByteVec): void { putUsize(out, _8.value[1]); const buf: rt.ByteVec = new rt.ByteVec(); const _19: Form.Form = Form.from$From_Version(version); - const _17: Encoder.Encoder = Encoder.new(buf, _19); - const _14: rt.Result = Probe.encode$Encode_Version(value, _17, version); + const _14: rt.Result = Probe.encode$Encode_Version(value, Encoder.new(buf, _19), version); if (_14.ok) { rt.byteVecExtendFromSlice(out, rt.byteVecView(buf)); } else { @@ -534,8 +510,7 @@ export function encodeMessages(data: Uint8Array, out: rt.ByteVec): void { const versions: Versions.Versions = Versions.from$From_Versions([{ _0: subscribe }, { _0: sequence }]); const buf: rt.ByteVec = new rt.ByteVec(); const _45: Form.Form = Form.from$From_Version(version); - const _43: Encoder.Encoder = Encoder.new(buf, _45); - const _40: rt.Result = Versions.encode$Encode_Version(versions, _43, version); + const _40: rt.Result = Versions.encode$Encode_Version(versions, Encoder.new(buf, _45), version); if (_40.ok) { rt.byteVecExtendFromSlice(out, rt.byteVecView(buf)); } else { @@ -604,8 +579,7 @@ export function errors(data: Uint8Array, out: rt.ByteVec): void { const _26: string = rt.fmtToString((f: rt.Formatter) => BoundsExceeded.fmt$Display(arg, f)); const arg2 = ([{}] as [BoundsExceeded.BoundsExceeded])[0]; const args2: rt.Fmt[] = [(f: rt.Formatter) => BoundsExceeded.fmt$Debug(arg2, f)]; - const _28: string = rt.fmtFormat([args2[0], " ", rt.fmtSpec({ alternate: true }, args2[0])]); - putText(out, _26, _28); + putText(out, _26, rt.fmtFormat([args2[0], " ", rt.fmtSpec({ alternate: true }, args2[0])])); break b0; } err = { tag: "MalformedAuthToken" } as DecodeError.DecodeError; @@ -615,8 +589,7 @@ export function errors(data: Uint8Array, out: rt.ByteVec): void { const _38: string = rt.fmtFormat([args4[0], " ", rt.fmtSpec({ align: ">", width: 30 }, args4[0]), "|"]); const arg4 = ([err] as [DecodeError.DecodeError])[0]; const args6: rt.Fmt[] = [(f: rt.Formatter) => DecodeError.fmt$Debug(arg4, f)]; - const _47: string = rt.fmtFormat([rt.fmtSpec({ alternate: true }, args6[0])]); - putText(out, _38, _47); + putText(out, _38, rt.fmtFormat([rt.fmtSpec({ alternate: true }, args6[0])])); decodeFailed(out, err); } } diff --git a/ts/fixtures/codec/expected/lite/group.Group.ts b/ts/fixtures/codec/expected/lite/group.Group.ts index d5b7e21ef..4182acc4a 100644 --- a/ts/fixtures/codec/expected/lite/group.Group.ts +++ b/ts/fixtures/codec/expected/lite/group.Group.ts @@ -15,9 +15,7 @@ export function decodeSlice$Decode_Version(buf: Uint8Array, version: Version.Ver const r: Decoder.Decoder = Decoder.new(buf, Form.from$From_Version(version)); const _6: rt.Result = decode$Decode_Version(r, version); if (_6.ok) { - const val: Group = _6.value; - const _0: rt.Result<[Group, rt.usize], DecodeError.DecodeError> = rt.Ok([val, rt.usizeSub(buf.length, Decoder.remaining(r))]); - return _0; + return rt.Ok([_6.value, rt.usizeSub(buf.length, Decoder.remaining(r))]); } return _6; } diff --git a/ts/fixtures/codec/expected/lite/message.ts b/ts/fixtures/codec/expected/lite/message.ts index a9aa09c58..69b00de5c 100644 --- a/ts/fixtures/codec/expected/lite/message.ts +++ b/ts/fixtures/codec/expected/lite/message.ts @@ -30,8 +30,7 @@ export function decodeSize(r: Decoder.Decoder, max: rt.usize): rt.Result rt.Result): rt.Result { const _3: rt.Result = decodeSize(r, 65535); if (_3.ok) { - const size: rt.usize = _3.value; - const _9: rt.Result = Decoder.sub(r, size); + const _9: rt.Result = Decoder.sub(r, _3.value); if (_9.ok) { const body: Decoder.Decoder = _9.value; const result: rt.Result = rt.resultAndThen(rt.resultMapErr(decode(body), DecodeError.complete), (msg: Group.Group): rt.Result => { @@ -57,8 +56,7 @@ export function decodeWith$Group_decode_closure0(r: Decoder.Decoder, decode: (a0 export function decodeWith$Probe_decode_closure0(r: Decoder.Decoder, decode: (a0: Decoder.Decoder) => rt.Result): rt.Result { const _3: rt.Result = decodeSize(r, 65535); if (_3.ok) { - const size: rt.usize = _3.value; - const _9: rt.Result = Decoder.sub(r, size); + const _9: rt.Result = Decoder.sub(r, _3.value); if (_9.ok) { const body: Decoder.Decoder = _9.value; const result: rt.Result = rt.resultAndThen(rt.resultMapErr(decode(body), DecodeError.complete), (msg: Probe.Probe): rt.Result => { diff --git a/ts/fixtures/codec/expected/lite/probe.Probe.ts b/ts/fixtures/codec/expected/lite/probe.Probe.ts index b2586ccd5..19da04a4a 100644 --- a/ts/fixtures/codec/expected/lite/probe.Probe.ts +++ b/ts/fixtures/codec/expected/lite/probe.Probe.ts @@ -16,9 +16,7 @@ export function decodeSlice$Decode_Version(buf: Uint8Array, version: Version.Ver const r: Decoder.Decoder = Decoder.new(buf, Form.from$From_Version(version)); const _6: rt.Result = decode$Decode_Version(r, version); if (_6.ok) { - const val: Probe = _6.value; - const _0: rt.Result<[Probe, rt.usize], DecodeError.DecodeError> = rt.Ok([val, rt.usizeSub(buf.length, Decoder.remaining(r))]); - return _0; + return rt.Ok([_6.value, rt.usizeSub(buf.length, Decoder.remaining(r))]); } return _6; } diff --git a/ts/fixtures/lang/expected/chars.ts b/ts/fixtures/lang/expected/chars.ts index 5b36bf8a6..d569e3a00 100644 --- a/ts/fixtures/lang/expected/chars.ts +++ b/ts/fixtures/lang/expected/chars.ts @@ -11,12 +11,9 @@ export function scalars(data: Uint8Array): rt.u32[] { if (!((rest.length === 0))) { const buf: Uint8Array = rt.bytes(4); const n: rt.usize = rt.min(rest.length, 4); - const _13: Uint8Array = rt.sliceRange(buf, 0, n); - const _17: Uint8Array = rest; - rt.sliceCopyFromSlice(_13, rt.sliceRange(_17, 0, n)); + rt.sliceCopyFromSlice(rt.sliceRange(buf, 0, n), rt.sliceRange(rest, 0, n)); all.push(rt.u32FromBeBytes(buf)); - const _24: Uint8Array = rest; - rest = rt.sliceRange(_24, n); + rest = rt.sliceRange(rest, n); } else { return all; } @@ -70,13 +67,7 @@ export function class_(c: rt.char): rt.u8 { export function chars(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _4: rt.u8 = rt.u8Rem(kind, 4); if (_4 === 0) { - const iterS: rt.u32[] = scalars(data); - let iterI: number = 0; - while (true) { - const _10: rt.u32 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_10 === rt.DONE) { - break; - } + for (const _10 of scalars(data)) { const _14: rt.char | undefined = rt.charFromU32(_10); if (_14 === undefined) { rt.byteVecPush(out, 255); @@ -87,14 +78,7 @@ export function chars(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } } } else if (_4 === 1) { - const iterS2: rt.u32[] = scalars(data); - let iterI2: number = 0; - while (true) { - const _27: rt.u32 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_27 === rt.DONE) { - break; - } - const n2: rt.u32 = _27; + for (const n2 of scalars(data)) { const c2: rt.char = rt.optionUnwrapOr(rt.charFromU32(n2), (n2 & 0xff) as rt.char); rt.byteVecPush(out, c2 & 0xff); rt.byteVecExtendFromSlice(out, rt.u16ToBeBytes(c2 & 0xffff)); @@ -120,9 +104,7 @@ export function chars(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } const i: rt.usize = _88[0]; const c3: rt.char = _88[1]; - const _96: rt.usize = rt.usizeRem(rt.usizeAdd(rt.usizeMul(i, 7), 3), cs.length); - const at = rt.idx(cs, _96); - const d: rt.char = cs[at]; + const d: rt.char = cs[rt.idx(cs, rt.usizeRem(rt.usizeAdd(rt.usizeMul(i, 7), 3), cs.length))]; rt.byteVecPush(out, (c3 < d ? 1 : 0) | (((c3 === d ? 1 : 0) << 1) & 0xff) | (((c3 >= 122 ? 1 : 0) << 2) & 0xff)); rt.byteVecPush(out, rt.hashAdd(seen, c3) ? 1 : 0); rt.btreeAdd(sorted, c3); @@ -136,13 +118,7 @@ export function chars(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(_128 as rt.u32)); } } else { - const iterS3: rt.u32[] = scalars(data); - let iterI3: number = 0; - while (true) { - const _140: rt.u32 | rt.Done = iterI3 < iterS3.length ? iterS3[iterI3++] : rt.DONE; - if (_140 === rt.DONE) { - break; - } + for (const _140 of scalars(data)) { const _144: rt.char | undefined = rt.charFromU32(_140); if (_144 !== undefined) { const arg = ([_144] as [rt.char])[0]; diff --git a/ts/fixtures/lang/expected/collections.ts b/ts/fixtures/lang/expected/collections.ts index d6c9624aa..0d9b2a13d 100644 --- a/ts/fixtures/lang/expected/collections.ts +++ b/ts/fixtures/lang/expected/collections.ts @@ -42,9 +42,7 @@ export function rankByte(r: Rank.Rank): rt.u8 { if (r.tag === "Mid") { return 16 | r._0; } - const x: rt.u8 = r.x; - const y: rt.u8 = r.y; - return 32 | ((x << 2) & 0xff) | y; + return 32 | ((r.x << 2) & 0xff) | r.y; } /** A `HashMap` by each kind of key, through a script of inserts, lookups, and removals. */ @@ -84,8 +82,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { return v4 & 0xff; })); } else { - const _48: rt.u16 = rt.u16Mul(v, 3); - rt.byteVecPush(out, rt.optionMapOr(rt.hashInsert(map, k, _48), 204, (old: rt.u16): rt.u8 => { + rt.byteVecPush(out, rt.optionMapOr(rt.hashInsert(map, k, rt.u16Mul(v, 3)), 204, (old: rt.u16): rt.u8 => { return old & 0xff; })); } @@ -288,17 +285,8 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { return t14.n & 0xff; })); } - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _380: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_380 === rt.DONE) { - break; - } - const b5: rt.u8 = _380; - const _387: rt.u8 = rt.u8Rem(b5, 8); - const _389: rt.u16 = b5 as rt.u16; - rt.byteVecPush(out, claim(copy2, _387, _389)); + for (const b5 of data) { + rt.byteVecPush(out, claim(copy2, rt.u8Rem(b5, 8), b5 as rt.u16)); } const stamped: rt.HashMap = rt.hashNew() as rt.HashMap; stamp(stamped); @@ -331,8 +319,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const h: rt.Hasher = _448[0]; const counted: Tally.Tally = copy$Tally(_448[1]); const _453: rt.Hasher = countedHasher(h, counted); - const _456: rt.u16 = counted.n; - rt.hashInt(_456, _453); + rt.hashInt(counted.n, _453); const want: rt.Hasher = rt.hasher(); rt.hashInt(rt.u16Add(first as rt.u16, 1), want); rt.byteVecPush(out, rt.u64Eq(rt.hashFinish(h), rt.hashFinish(want)) ? 1 : 0); @@ -357,20 +344,12 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, rt.hashLen(tuples) & 0xff); } else { const words: rt.HashMap = rt.hashNew() as rt.HashMap; - const iterS2: Uint8Array = data; - let iterI2: number = 0; - while (true) { - const _496: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_496 === rt.DONE) { - break; - } - const b6: rt.u8 = _496; + for (const b6 of data) { const _502: rt.usize = rt.usizeRem(b6 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); if (!(_502 < 8)) { rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _502); } - const word: string = ["", "a", "ab", "b", "é", "", "￿", "𐀀"][_502]; - rt.byteVecPush(rt.entryOrInsertWith(rt.entry(words, word), (): rt.ByteVec => { + rt.byteVecPush(rt.entryOrInsertWith(rt.entry(words, ["", "a", "ab", "b", "é", "", "￿", "𐀀"][_502]), (): rt.ByteVec => { return new rt.ByteVec(); }), b6); } @@ -381,9 +360,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { if (_517 === rt.DONE) { break; } - const _524: string = _517[0]; - const _525: rt.usize = _517[1].length; - rt.btreeInsert(lens, _524, _525); + rt.btreeInsert(lens, _517[0], _517[1].length); } const iter17: rt.Iter<[string, rt.usize]> = rt.btreeIter(lens); while (true) { @@ -460,8 +437,7 @@ export function claim(map: rt.HashMap, k: rt.u8, n: rt.u16): if (!(rt.u16Rem(rt.entryGet(_4).n, 2) === 0)) { return rt.entryRemove(_4).n & 0xff; } - const e: rt.Entry = _4; - const t: Tally.Tally = rt.entryGet(e); + const t: Tally.Tally = rt.entryGet(_4); t.n = rt.u16Add(t.n, n); return 1; } @@ -475,14 +451,7 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { if (_4 === 0) { const hashed: rt.HashSet = rt.hashNew() as rt.HashSet; const sorted: rt.BTreeSet = rt.btreeNew(rt.cmp) as rt.BTreeSet; - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _10: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_10 === rt.DONE) { - break; - } - const b: rt.u8 = _10; + for (const b of data) { const v: rt.u16 = rt.u16Rem(b as rt.u16, 24); const _17: rt.u8 = rt.u8Rem(b, 3); if (_17 === 0) { @@ -524,14 +493,7 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_4 === 1) { const nibbles: rt.BTreeSet = rt.btreeNew(Nibble.cmp$Ord) as rt.BTreeSet; const seen: rt.HashSet = rt.hashNew(rt.hashing(Nibble.hash$Hash_DefaultHasher, Nibble.eq$PartialEq)) as rt.HashSet; - const iterS2: Uint8Array = data; - let iterI2: number = 0; - while (true) { - const _106: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_106 === rt.DONE) { - break; - } - const b2: rt.u8 = _106; + for (const b2 of data) { rt.byteVecPush(out, rt.btreeAdd(nibbles, { _0: b2 }) ? 1 : 0); rt.byteVecPush(out, rt.hashAdd(seen, { _0: b2 }) ? 1 : 0); } @@ -558,13 +520,7 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } rt.byteVecPush(out, rt.hashLen(seen) & 0xff); const dirs: rt.HashSet = rt.hashNew(rt.hashing(Dir.hash$Hash_DefaultHasher, Dir.eq$PartialEq, true)) as rt.HashSet; - const iterS3: Uint8Array = data; - let iterI3: number = 0; - while (true) { - const _151: rt.u8 | rt.Done = iterI3 < iterS3.length ? iterS3[iterI3++] : rt.DONE; - if (_151 === rt.DONE) { - break; - } + for (const _151 of data) { const _160: rt.usize = rt.usizeRem(_151 as rt.usize, 3); if (!(_160 < 3)) { rt.panic("index out of bounds: the len is " + 3 + " but the index is " + _160); @@ -574,13 +530,7 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, rt.hashLen(dirs) & 0xff); } else { const words: rt.BTreeSet = rt.btreeNew(rt.cmpStr) as rt.BTreeSet; - const iterS4: Uint8Array = data; - let iterI4: number = 0; - while (true) { - const _175: rt.u8 | rt.Done = iterI4 < iterS4.length ? iterS4[iterI4++] : rt.DONE; - if (_175 === rt.DONE) { - break; - } + for (const _175 of data) { const _182: rt.usize = rt.usizeRem(_175 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); if (!(_182 < 8)) { rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _182); @@ -736,14 +686,7 @@ export function btreeMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void if (_197 !== undefined) { _197.n = _197.n ^ 23130; } - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _205: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_205 === rt.DONE) { - break; - } - const b2: rt.u8 = _205; + for (const b2 of data) { const r: Rank.Rank = rank(b2, rt.u8Div(b2, 3)); const _212: rt.Entry = rt.entry(ranks, r); if (!rt.entryOccupied(_212)) { @@ -751,11 +694,9 @@ export function btreeMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void rt.byteVecPush(out, rankByte(rt.entryKey(e))); rt.entryOrInsert(e, { n: b2 as rt.u16 }); } else if (!(rt.entryGet(_212).n > 256)) { - const e3: rt.Entry = _212; - rt.byteVecPush(out, rt.entryInsert(e3, { n: 512 }).n & 0xff); + rt.byteVecPush(out, rt.entryInsert(_212, { n: 512 }).n & 0xff); } else { - const _230: [Rank.Rank, Tally.Tally] = rt.entryRemoveEntry(_212); - rt.byteVecPush(out, rankByte(_230[0])); + rt.byteVecPush(out, rankByte(rt.entryRemoveEntry(_212)[0])); } } const iter7: rt.Iter<[Rank.Rank, Tally.Tally]> = rt.btreeIter(ranks); @@ -802,14 +743,7 @@ export function btreeMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void } else { const nibbles: rt.BTreeMap = rt.btreeNew(Nibble.cmp$Ord) as rt.BTreeMap; const words: rt.BTreeMap = rt.btreeNew(rt.cmpStr) as rt.BTreeMap; - const iterS2: Uint8Array = data; - let iterI2: number = 0; - while (true) { - const _307: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_307 === rt.DONE) { - break; - } - const b3: rt.u8 = _307; + for (const b3 of data) { rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeInsert(nibbles, { _0: b3 }, b3), 204)); const _320: rt.usize = rt.usizeRem(b3 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); if (!(_320 < 8)) { @@ -911,14 +845,7 @@ export function deques(data: Uint8Array, out: rt.ByteVec): void { let drained2!: rt.ByteVec; const q: rt.VecDeque = rt.dequeNew() as rt.VecDeque; const pairs: rt.VecDeque<[rt.u8, rt.u8]> = rt.dequeNew() as rt.VecDeque<[rt.u8, rt.u8]>; - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _7: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_7 === rt.DONE) { - break; - } - const b: rt.u8 = _7; + for (const b of data) { const _12: rt.u8 = rt.u8Rem(b, 7); if (_12 === 0) { rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequePopFront(q), 238)); @@ -929,8 +856,7 @@ export function deques(data: Uint8Array, out: rt.ByteVec): void { } else if (_12 === 3) { rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequeEnd(q), 236)); rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequeEnd(q, true), 235)); - const _36: rt.usize = rt.usizeRem(b as rt.usize, 5); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequeGet(q, _36), 234)); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequeGet(q, rt.usizeRem(b as rt.usize, 5)), 234)); } else { rt.dequePushBack(q, b); } @@ -945,8 +871,7 @@ export function deques(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, q.n & 0xff); rt.iterExtendBytes(out, rt.iterRev(rt.dequeIter(q))); if (!((q.n === 0))) { - const _71: rt.usize = rt.usizeDiv(q.n, 2); - rt.byteVecPush(out, rt.dequeIndex(q, _71)); + rt.byteVecPush(out, rt.dequeIndex(q, rt.usizeDiv(q.n, 2))); } rt.dequeRetain(q, (b3: rt.u8): boolean => { return rt.u8Rem(b3, 2) === 0; @@ -991,8 +916,7 @@ export function deques(data: Uint8Array, out: rt.ByteVec): void { })); const _135: rt.Iter = rt.iterSlice(data); rt.dequeExtend(q, _135); - const _139: rt.usize = rt.usizeDiv(q.n, 2); - rt.dequeInsert(q, _139, 66); + rt.dequeInsert(q, rt.usizeDiv(q.n, 2), 66); rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequeRemove(q, 1), 233)); rt.dequeTruncate(q, 5); rt.byteVecPush(out, rt.dequeContains(q, 66, rt.same) ? 1 : 0); @@ -1025,8 +949,7 @@ export function vecs(data: Uint8Array, out: rt.ByteVec): void { const n: rt.usize = rt.usizeRem(rt.optionUnwrapOr(rt.sliceGet(data, 2), 0) as rt.usize, 5); const _16: rt.Result = rt.stringFromUtf8(rt.sliceToByteVec(data)); if (_16.ok) { - const s: string = _16.value; - name = s; + name = _16.value; } else { name = "?"; } @@ -1035,27 +958,19 @@ export function vecs(data: Uint8Array, out: rt.ByteVec): void { pairs.push([b, a as rt.u16] as [rt.u8, rt.u16]); const at = rt.idx(pairs, 0); pairs[at][0] = pairs[at][0] ^ 255; - const iterS: [rt.u8, rt.u16][] = pairs; - let iterI: number = 0; - while (true) { - const _39: [rt.u8, rt.u16] | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_39 === rt.DONE) { - break; - } + for (const _39 of pairs) { rt.byteVecPush(out, _39[0] ^ (_39[1] & 0xff)); } rt.byteVecPush(out, [name, "x", name].length & 0xff); const one: Cloned.Cloned[] = [{ depth: a, name: name }]; - const at2 = rt.idx(one, 0); - rt.byteVecPush(out, one[at2].depth); + rt.byteVecPush(out, one[rt.idx(one, 0)].depth); rt.byteVecExtendFromSlice(out, rt.byteVecView(rt.byteVecOf(b, n))); rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(rt.vecFromElem(rt.u16Mul(a as rt.u16, 257), n, undefined)), (w: rt.u16): rt.u8 => { return rt.u16Shr(w, 4) & 0xff; })); const tuples: [rt.u8, rt.u8][] = rt.vecFromElem(copy$u8_u8([a, b] as [rt.u8, rt.u8]), n, copy$u8_u8); if (n > 0) { - const at3 = rt.idx(tuples, 0); - tuples[at3][0] = 238; + tuples[rt.idx(tuples, 0)][0] = 238; } rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(tuples), (t: [rt.u8, rt.u8]): rt.u8 => { return t[0] ^ t[1]; @@ -1065,8 +980,7 @@ export function vecs(data: Uint8Array, out: rt.ByteVec): void { rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(cloned), (c: Cloned.Cloned): rt.u8 => { return c.depth; })); - const _113: rt.Iter = rt.iterSlice(cloned); - rt.byteVecPush(out, rt.iterAll(_113, (c2: Cloned.Cloned): boolean => { + rt.byteVecPush(out, rt.iterAll(rt.iterSlice(cloned), (c2: Cloned.Cloned): boolean => { return rt.stringLen(c2.name) === data.length; }) ? 1 : 0); rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(rt.vecFromElem(copy$Bumped({ _0: b }), n, Bumped.clone$Clone)), (o: Bumped.Bumped): rt.u8 => { @@ -1082,17 +996,12 @@ export function vecs(data: Uint8Array, out: rt.ByteVec): void { const bumps: Bumped.Bumped[] = rt.vecFromElem(copy$Bumped(held), n, Bumped.clone$Clone); const kept: Bumped.Bumped[] = rt.vecFromElem(copy$Bumped(held), n, Bumped.clone$Clone); if (n > 0) { - const _137: rt.usize = rt.usizeSub(n, 1); - const at5 = rt.idx(repeated, _137); + const at5 = rt.idx(repeated, rt.usizeSub(n, 1)); repeated[at5][1] = repeated[at5][1] ^ 255; - const _141: rt.usize = rt.usizeSub(n, 1); - const at6 = rt.idx(bumps, _141); + const at6 = rt.idx(bumps, rt.usizeSub(n, 1)); bumps[at6]._0 = bumps[at6]._0 ^ 255; } - const _147: rt.u8 = a; - const _148: rt.u8 = b; - const at7 = rt.idx(listed, 1); - rt.byteVecExtendFromSlice(out, Uint8Array.of(_147, _148, listed[at7][0], a)); + rt.byteVecExtendFromSlice(out, Uint8Array.of(a, b, listed[rt.idx(listed, 1)][0], a)); rt.iterExtendBytes(out, rt.iterMap(rt.iterChain(rt.iterSlice(repeated), rt.iterSlice(again)), (t2: [rt.u8, rt.u8]): rt.u8 => { return t2[1]; })); diff --git a/ts/fixtures/lang/expected/fmt.Fails.ts b/ts/fixtures/lang/expected/fmt.Fails.ts index ad398b210..cd64c4e18 100644 --- a/ts/fixtures/lang/expected/fmt.Fails.ts +++ b/ts/fixtures/lang/expected/fmt.Fails.ts @@ -11,8 +11,7 @@ export function fmt$Display(self: Fails, f: rt.Formatter): rt.Result rt.u8Display(arg, f)]; - const _8: rt.Result = rt.fmtWriteFmt(f, ["half ", args2[0]]); - if (_8.ok) { + if (rt.fmtWriteFmt(f, ["half ", args2[0]]).ok) { return rt.Err(new rt.FmtError()); } return rt.Err(new rt.FmtError()); diff --git a/ts/fixtures/lang/expected/fmt.Manual.ts b/ts/fixtures/lang/expected/fmt.Manual.ts index 3290a5e99..4f2f5f506 100644 --- a/ts/fixtures/lang/expected/fmt.Manual.ts +++ b/ts/fixtures/lang/expected/fmt.Manual.ts @@ -9,8 +9,7 @@ export interface Manual { } export function fmt$Debug(self: Manual, f: rt.Formatter): rt.Result { - const _6: rt.DebugStruct = rt.fmtDebugStruct(f, "Manual"); - return rt.debugStructFinishNonExhaustive(rt.debugStructField(rt.debugStructField(_6, "id", (f: rt.Formatter) => rt.u8Display(self.id, f)), "list", (f: rt.Formatter) => rt.fmtList(self.list, f, rt.u16Display))); + return rt.debugStructFinishNonExhaustive(rt.debugStructField(rt.debugStructField(rt.fmtDebugStruct(f, "Manual"), "id", (f: rt.Formatter) => rt.u8Display(self.id, f)), "list", (f: rt.Formatter) => rt.fmtList(self.list, f, rt.u16Display))); } //# sourceMappingURL=fmt.Manual.ts.map diff --git a/ts/fixtures/lang/expected/fmt.Nested.ts b/ts/fixtures/lang/expected/fmt.Nested.ts index 016843b50..0affd4ea2 100644 --- a/ts/fixtures/lang/expected/fmt.Nested.ts +++ b/ts/fixtures/lang/expected/fmt.Nested.ts @@ -9,8 +9,7 @@ import * as Shape from "./shapes.Shape.ts"; export function fmt$Debug(self: Nested, f: rt.Formatter): rt.Result { const names: string[] = ["name", "point", "shape", "tags", "pairs", "maybe", "none", "result", "list", "tuple", "single", "empty", "unit", "boxed"]; const values: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtStr(self.name, f), (f: rt.Formatter) => Point.fmt$Debug(self.point, f), (f: rt.Formatter) => Shape.fmt$Debug(self.shape, f), (f: rt.Formatter) => rt.fmtList(rt.byteVecView(self.tags), f, rt.u8Display), (f: rt.Formatter) => rt.fmtList(self.pairs, f, (value: Pair.Pair, f: rt.Formatter) => Pair.fmt$Debug(value, f)), (f: rt.Formatter) => rt.fmtOption(self.maybe, f, (value: Pair.Pair, f: rt.Formatter) => Pair.fmt$Debug(value, f)), (f: rt.Formatter) => rt.fmtOption(self.none, f, rt.u8Display), (f: rt.Formatter) => rt.fmtResult(self.result, f, rt.u8Display, rt.fmtStr), (f: rt.Formatter) => rt.fmtList(self.list, f, rt.i16Display), (f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.u8Display(self.tuple[0], f), (f: rt.Formatter) => rt.fmtBool(self.tuple[1], f), (f: rt.Formatter) => rt.fmtStr(self.tuple[2], f)], f), (f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.u8Display(self.single[0], f)], f), (f: rt.Formatter) => rt.fmtList(rt.byteVecView(self.empty), f, rt.u8Display), (f: rt.Formatter) => rt.fmtUnit(self.unit, f), (f: rt.Formatter) => Kind.fmt$Debug(self.boxed, f)]; - const _36: string = "Nested"; - return rt.fmtDebugStructFields(f, _36, names, values); + return rt.fmtDebugStructFields(f, "Nested", names, values); } export interface Nested { diff --git a/ts/fixtures/lang/expected/fmt.Six.ts b/ts/fixtures/lang/expected/fmt.Six.ts index c6a4d3718..ce8fbbd1c 100644 --- a/ts/fixtures/lang/expected/fmt.Six.ts +++ b/ts/fixtures/lang/expected/fmt.Six.ts @@ -4,8 +4,7 @@ import * as rt from "./rt.ts"; export function fmt$Debug(self: Six, f: rt.Formatter): rt.Result { const values: rt.Fmt[] = [(f: rt.Formatter) => rt.u8Display(self._0, f), (f: rt.Formatter) => rt.u8Display(self._1, f), (f: rt.Formatter) => rt.u8Display(self._2, f), (f: rt.Formatter) => rt.u8Display(self._3, f), (f: rt.Formatter) => rt.u8Display(self._4, f), (f: rt.Formatter) => rt.u8Display(self._5, f)]; - const _19: string = "Six"; - return rt.fmtDebugTupleFields(f, _19, values); + return rt.fmtDebugTupleFields(f, "Six", values); } export interface Six { diff --git a/ts/fixtures/lang/expected/fmt.Tup.ts b/ts/fixtures/lang/expected/fmt.Tup.ts index 03986f37c..bd7cf3500 100644 --- a/ts/fixtures/lang/expected/fmt.Tup.ts +++ b/ts/fixtures/lang/expected/fmt.Tup.ts @@ -9,11 +9,9 @@ export interface Tup { export function fmt$Debug(self: Tup, f: rt.Formatter): rt.Result { if (self._1 === undefined) { - const _15: rt.DebugTuple = rt.fmtDebugTuple(f, "Tup"); - return rt.debugTupleFinishNonExhaustive(rt.debugTupleField(_15, (f: rt.Formatter) => rt.u8Display(self._0, f))); + return rt.debugTupleFinishNonExhaustive(rt.debugTupleField(rt.fmtDebugTuple(f, "Tup"), (f: rt.Formatter) => rt.u8Display(self._0, f))); } - const _7: rt.DebugTuple = rt.fmtDebugTuple(f, "Tup"); - return rt.debugTupleFinish(rt.debugTupleField(rt.debugTupleField(_7, (f: rt.Formatter) => rt.u8Display(self._0, f)), (f: rt.Formatter) => rt.fmtOption(self._1, f, rt.u8Display))); + return rt.debugTupleFinish(rt.debugTupleField(rt.debugTupleField(rt.fmtDebugTuple(f, "Tup"), (f: rt.Formatter) => rt.u8Display(self._0, f)), (f: rt.Formatter) => rt.fmtOption(self._1, f, rt.u8Display))); } //# sourceMappingURL=fmt.Tup.ts.map diff --git a/ts/fixtures/lang/expected/fmt.Wide.ts b/ts/fixtures/lang/expected/fmt.Wide.ts index d69a29bbd..992edf388 100644 --- a/ts/fixtures/lang/expected/fmt.Wide.ts +++ b/ts/fixtures/lang/expected/fmt.Wide.ts @@ -5,8 +5,7 @@ import * as rt from "./rt.ts"; export function fmt$Debug(self: Wide, f: rt.Formatter): rt.Result { const names: string[] = ["a", "b", "c", "d", "e", "f"]; const values: rt.Fmt[] = [(f: rt.Formatter) => rt.u8Display(self.a, f), (f: rt.Formatter) => rt.u16Display(self.b, f), (f: rt.Formatter) => rt.u32Display(self.c, f), (f: rt.Formatter) => rt.u64Display(self.d, f), (f: rt.Formatter) => rt.i8Display(self.e, f), (f: rt.Formatter) => rt.fmtBool(self.f, f)]; - const _20: string = "Wide"; - return rt.fmtDebugStructFields(f, _20, names, values); + return rt.fmtDebugStructFields(f, "Wide", names, values); } /** Past five fields, derived `Debug` takes the fields as slices. */ diff --git a/ts/fixtures/lang/expected/fmt.ts b/ts/fixtures/lang/expected/fmt.ts index 5955d67a1..9076384ae 100644 --- a/ts/fixtures/lang/expected/fmt.ts +++ b/ts/fixtures/lang/expected/fmt.ts @@ -129,13 +129,7 @@ export function ints(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { /** Strings padded and escaped, and bytes that may not be UTF-8. */ export function strings(data: Uint8Array, out: rt.ByteVec): void { let flag!: boolean; - const iterS: Uint8Array = rt.sliceRange(data, 0, rt.min(data.length, 3)); - let iterI: number = 0; - while (true) { - const _9: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_9 === rt.DONE) { - break; - } + for (const _9 of rt.sliceRange(data, 0, rt.min(data.length, 3))) { const _15: rt.usize = rt.usizeRem(_9 as rt.usize, ["", "a", "héllo", "日本語", "tab\tnew\nline\r", "quote\"back\\slash'", "\u0000\u0001\u001f", "€Ÿ ­", "é", "‍ᅟ\u2028 ", "͸􏿽", "😀 🇦", "゙゚ン", "{}"].length); if (!(_15 < 14)) { rt.panic("index out of bounds: the len is " + 14 + " but the index is " + _15); @@ -432,20 +426,16 @@ export function panics(kind: rt.u8, rest: Uint8Array, out: rt.ByteVec): void { put(out, rt.fmtFormat([args16[0], " ", args16[1]])); } else if (_7 === 15) { const buf: Uint8Array = rt.bytes(3); - const _202: Uint8Array = buf; - const part3 = rt.min(rest.length, 4); - rt.sliceCopyFromSlice(_202, rt.sliceRange(rest, 0, part3)); + rt.sliceCopyFromSlice(buf, rt.sliceRange(rest, 0, rt.min(rest.length, 4))); const arg4 = ([buf] as [Uint8Array])[0]; const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(arg4, f, rt.u8Display)]; put(out, rt.fmtFormat([args18[0]])); } else if (_7 === 16) { const _221: rt.Result = rt.stringFromUtf8(rt.sliceToByteVec(rest)); if (_221.ok) { - const _225: rt.u8 = rt.stringLen(_221.value) & 0xff; - r4 = rt.Ok(_225); + r4 = rt.Ok(rt.stringLen(_221.value) & 0xff); } else { - const e: rt.FromUtf8Error = _221.error; - r4 = rt.Err(e); + r4 = rt.Err(_221.error); } const _234: rt.u8 = rt.resultUnwrap(r4, rt.fmtFromUtf8ErrorDebug); put(out, rt.fmtToString((f: rt.Formatter) => rt.u8Display(_234, f))); @@ -454,8 +444,7 @@ export function panics(kind: rt.u8, rest: Uint8Array, out: rt.ByteVec): void { const part = rt.u8Rem(n, 6) as rt.usize; const part2 = rt.u8Rem(rt.u8Div(n, 6), 6) as rt.usize; const dest: rt.usize = rt.usizeRem(rt.optionUnwrapOr(rt.sliceGet(rest, 1), 0) as rt.usize, 4); - const _244: Uint8Array = buf2; - rt.sliceCopyWithin(_244, part, part2, dest); + rt.sliceCopyWithin(buf2, part, part2, dest); const arg3 = ([buf2] as [Uint8Array])[0]; const args20: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(arg3, f, rt.u8Display)]; put(out, rt.fmtFormat([args20[0]])); diff --git a/ts/fixtures/lang/expected/ints.ts b/ts/fixtures/lang/expected/ints.ts index d0dc26415..12f2f4af8 100644 --- a/ts/fixtures/lang/expected/ints.ts +++ b/ts/fixtures/lang/expected/ints.ts @@ -24,9 +24,7 @@ export function u8Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.u8 = _6[0]; const buf2: Uint8Array = Uint8Array.of(0); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.u8 = rt.u8FromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.u8, Uint8Array]; @@ -34,20 +32,15 @@ export function u8Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 8); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.u8Add(a, b); - _50(out, part16); + _50(out, rt.u8Add(a, b)); } else if (_52 === 1) { - const part15 = rt.u8Sub(a, b); - _50(out, part15); + _50(out, rt.u8Sub(a, b)); } else if (_52 === 2) { - const part14 = rt.u8Mul(a, b); - _50(out, part14); + _50(out, rt.u8Mul(a, b)); } else if (_52 === 3) { - const part13 = rt.u8Div(a, b); - _50(out, part13); + _50(out, rt.u8Div(a, b)); } else if (_52 === 4) { - const part12 = rt.u8Rem(a, b); - _50(out, part12); + _50(out, rt.u8Rem(a, b)); } else if (_52 === 5) { _50(out, a & b); } else if (_52 === 6) { @@ -55,11 +48,9 @@ export function u8Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, a ^ b); } else if (_52 === 8) { - const part11 = rt.u8Shl(a, shift); - _50(out, part11); + _50(out, rt.u8Shl(a, shift)); } else if (_52 === 9) { - const part10 = rt.u8Shr(a, shift); - _50(out, part10); + _50(out, rt.u8Shr(a, shift)); } else if (_52 === 10) { _50(out, ~a & 0xff); } else if (_52 === 11) { @@ -88,11 +79,9 @@ export function u8Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.u8LeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.max(a, b); - _50(out, part2); + _50(out, rt.max(a, b)); } else if (_52 === 21) { - const part = rt.min(a, b); - _50(out, part); + _50(out, rt.min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, a === b ? 1 : 0); rt.byteVecPush(out, a < b ? 1 : 0); @@ -141,9 +130,7 @@ export function u16Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.u16 = _6[0]; const buf2: Uint8Array = rt.bytes(2); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.u16 = rt.u16FromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.u16, Uint8Array]; @@ -151,20 +138,15 @@ export function u16Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 16); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.u16Add(a, b); - _50(out, part16); + _50(out, rt.u16Add(a, b)); } else if (_52 === 1) { - const part15 = rt.u16Sub(a, b); - _50(out, part15); + _50(out, rt.u16Sub(a, b)); } else if (_52 === 2) { - const part14 = rt.u16Mul(a, b); - _50(out, part14); + _50(out, rt.u16Mul(a, b)); } else if (_52 === 3) { - const part13 = rt.u16Div(a, b); - _50(out, part13); + _50(out, rt.u16Div(a, b)); } else if (_52 === 4) { - const part12 = rt.u16Rem(a, b); - _50(out, part12); + _50(out, rt.u16Rem(a, b)); } else if (_52 === 5) { _50(out, a & b); } else if (_52 === 6) { @@ -172,11 +154,9 @@ export function u16Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, a ^ b); } else if (_52 === 8) { - const part11 = rt.u16Shl(a, shift); - _50(out, part11); + _50(out, rt.u16Shl(a, shift)); } else if (_52 === 9) { - const part10 = rt.u16Shr(a, shift); - _50(out, part10); + _50(out, rt.u16Shr(a, shift)); } else if (_52 === 10) { _50(out, ~a & 0xffff); } else if (_52 === 11) { @@ -205,11 +185,9 @@ export function u16Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.u16LeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.max(a, b); - _50(out, part2); + _50(out, rt.max(a, b)); } else if (_52 === 21) { - const part = rt.min(a, b); - _50(out, part); + _50(out, rt.min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, a === b ? 1 : 0); rt.byteVecPush(out, a < b ? 1 : 0); @@ -258,9 +236,7 @@ export function u32Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.u32 = _6[0]; const buf2: Uint8Array = rt.bytes(4); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.u32 = rt.u32FromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.u32, Uint8Array]; @@ -268,20 +244,15 @@ export function u32Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.u32Add(a, b); - _50(out, part16); + _50(out, rt.u32Add(a, b)); } else if (_52 === 1) { - const part15 = rt.u32Sub(a, b); - _50(out, part15); + _50(out, rt.u32Sub(a, b)); } else if (_52 === 2) { - const part14 = rt.u32Mul(a, b); - _50(out, part14); + _50(out, rt.u32Mul(a, b)); } else if (_52 === 3) { - const part13 = rt.u32Div(a, b); - _50(out, part13); + _50(out, rt.u32Div(a, b)); } else if (_52 === 4) { - const part12 = rt.u32Rem(a, b); - _50(out, part12); + _50(out, rt.u32Rem(a, b)); } else if (_52 === 5) { _50(out, (a & b) >>> 0); } else if (_52 === 6) { @@ -289,11 +260,9 @@ export function u32Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, (a ^ b) >>> 0); } else if (_52 === 8) { - const part11 = rt.u32Shl(a, shift); - _50(out, part11); + _50(out, rt.u32Shl(a, shift)); } else if (_52 === 9) { - const part10 = rt.u32Shr(a, shift); - _50(out, part10); + _50(out, rt.u32Shr(a, shift)); } else if (_52 === 10) { _50(out, ~a >>> 0); } else if (_52 === 11) { @@ -322,11 +291,9 @@ export function u32Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.u32LeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.max(a, b); - _50(out, part2); + _50(out, rt.max(a, b)); } else if (_52 === 21) { - const part = rt.min(a, b); - _50(out, part); + _50(out, rt.min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, a === b ? 1 : 0); rt.byteVecPush(out, a < b ? 1 : 0); @@ -375,9 +342,7 @@ export function u64Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.u64 = _6[0]; const buf2: Uint8Array = rt.bytes(8); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.u64 = rt.u64FromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.u64, Uint8Array]; @@ -385,20 +350,15 @@ export function u64Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 64); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.u64Add(a, b); - _50(out, part16); + _50(out, rt.u64Add(a, b)); } else if (_52 === 1) { - const part15 = rt.u64Sub(a, b); - _50(out, part15); + _50(out, rt.u64Sub(a, b)); } else if (_52 === 2) { - const part14 = rt.u64Mul(a, b); - _50(out, part14); + _50(out, rt.u64Mul(a, b)); } else if (_52 === 3) { - const part13 = rt.u64Div(a, b); - _50(out, part13); + _50(out, rt.u64Div(a, b)); } else if (_52 === 4) { - const part12 = rt.u64Rem(a, b); - _50(out, part12); + _50(out, rt.u64Rem(a, b)); } else if (_52 === 5) { _50(out, rt.u64And(a, b)); } else if (_52 === 6) { @@ -406,11 +366,9 @@ export function u64Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, rt.u64Xor(a, b)); } else if (_52 === 8) { - const part11 = rt.u64Shl(a, shift); - _50(out, part11); + _50(out, rt.u64Shl(a, shift)); } else if (_52 === 9) { - const part10 = rt.u64Shr(a, shift); - _50(out, part10); + _50(out, rt.u64Shr(a, shift)); } else if (_52 === 10) { _50(out, rt.u64Not(a)); } else if (_52 === 11) { @@ -439,11 +397,9 @@ export function u64Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.u64LeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.u64Max(a, b); - _50(out, part2); + _50(out, rt.u64Max(a, b)); } else if (_52 === 21) { - const part = rt.u64Min(a, b); - _50(out, part); + _50(out, rt.u64Min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, rt.u64Eq(a, b) ? 1 : 0); rt.byteVecPush(out, rt.u64Lt(a, b) ? 1 : 0); @@ -492,9 +448,7 @@ export function u128Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.u128 = _6[0]; const buf2: Uint8Array = rt.bytes(16); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.u128 = rt.u128FromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.u128, Uint8Array]; @@ -502,20 +456,15 @@ export function u128Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 128); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.u128Add(a, b); - _50(out, part16); + _50(out, rt.u128Add(a, b)); } else if (_52 === 1) { - const part15 = rt.u128Sub(a, b); - _50(out, part15); + _50(out, rt.u128Sub(a, b)); } else if (_52 === 2) { - const part14 = rt.u128Mul(a, b); - _50(out, part14); + _50(out, rt.u128Mul(a, b)); } else if (_52 === 3) { - const part13 = rt.u128Div(a, b); - _50(out, part13); + _50(out, rt.u128Div(a, b)); } else if (_52 === 4) { - const part12 = rt.u128Rem(a, b); - _50(out, part12); + _50(out, rt.u128Rem(a, b)); } else if (_52 === 5) { _50(out, rt.u128And(a, b)); } else if (_52 === 6) { @@ -523,11 +472,9 @@ export function u128Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, rt.u128Xor(a, b)); } else if (_52 === 8) { - const part11 = rt.u128Shl(a, shift); - _50(out, part11); + _50(out, rt.u128Shl(a, shift)); } else if (_52 === 9) { - const part10 = rt.u128Shr(a, shift); - _50(out, part10); + _50(out, rt.u128Shr(a, shift)); } else if (_52 === 10) { _50(out, rt.u128Not(a)); } else if (_52 === 11) { @@ -556,11 +503,9 @@ export function u128Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.u128LeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.u128Max(a, b); - _50(out, part2); + _50(out, rt.u128Max(a, b)); } else if (_52 === 21) { - const part = rt.u128Min(a, b); - _50(out, part); + _50(out, rt.u128Min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, rt.u128Eq(a, b) ? 1 : 0); rt.byteVecPush(out, rt.u128Lt(a, b) ? 1 : 0); @@ -609,9 +554,7 @@ export function usizeOp(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.usize = _6[0]; const buf2: Uint8Array = rt.bytes(4); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.usize = rt.usizeFromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.usize, Uint8Array]; @@ -619,20 +562,15 @@ export function usizeOp(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.usizeAdd(a, b); - _50(out, part16); + _50(out, rt.usizeAdd(a, b)); } else if (_52 === 1) { - const part15 = rt.usizeSub(a, b); - _50(out, part15); + _50(out, rt.usizeSub(a, b)); } else if (_52 === 2) { - const part14 = rt.usizeMul(a, b); - _50(out, part14); + _50(out, rt.usizeMul(a, b)); } else if (_52 === 3) { - const part13 = rt.usizeDiv(a, b); - _50(out, part13); + _50(out, rt.usizeDiv(a, b)); } else if (_52 === 4) { - const part12 = rt.usizeRem(a, b); - _50(out, part12); + _50(out, rt.usizeRem(a, b)); } else if (_52 === 5) { _50(out, (a & b) >>> 0); } else if (_52 === 6) { @@ -640,11 +578,9 @@ export function usizeOp(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, (a ^ b) >>> 0); } else if (_52 === 8) { - const part11 = rt.usizeShl(a, shift); - _50(out, part11); + _50(out, rt.usizeShl(a, shift)); } else if (_52 === 9) { - const part10 = rt.usizeShr(a, shift); - _50(out, part10); + _50(out, rt.usizeShr(a, shift)); } else if (_52 === 10) { _50(out, ~a >>> 0); } else if (_52 === 11) { @@ -673,11 +609,9 @@ export function usizeOp(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.usizeLeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.max(a, b); - _50(out, part2); + _50(out, rt.max(a, b)); } else if (_52 === 21) { - const part = rt.min(a, b); - _50(out, part); + _50(out, rt.min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, a === b ? 1 : 0); rt.byteVecPush(out, a < b ? 1 : 0); @@ -726,9 +660,7 @@ export function i8Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.i8 = _6[0]; const buf2: Uint8Array = Uint8Array.of(0); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.i8 = rt.i8FromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.i8, Uint8Array]; @@ -736,20 +668,15 @@ export function i8Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 8); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.i8Add(a, b); - _50(out, part16); + _50(out, rt.i8Add(a, b)); } else if (_52 === 1) { - const part15 = rt.i8Sub(a, b); - _50(out, part15); + _50(out, rt.i8Sub(a, b)); } else if (_52 === 2) { - const part14 = rt.i8Mul(a, b); - _50(out, part14); + _50(out, rt.i8Mul(a, b)); } else if (_52 === 3) { - const part13 = rt.i8Div(a, b); - _50(out, part13); + _50(out, rt.i8Div(a, b)); } else if (_52 === 4) { - const part12 = rt.i8Rem(a, b); - _50(out, part12); + _50(out, rt.i8Rem(a, b)); } else if (_52 === 5) { _50(out, a & b); } else if (_52 === 6) { @@ -757,11 +684,9 @@ export function i8Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, a ^ b); } else if (_52 === 8) { - const part11 = rt.i8Shl(a, shift); - _50(out, part11); + _50(out, rt.i8Shl(a, shift)); } else if (_52 === 9) { - const part10 = rt.i8Shr(a, shift); - _50(out, part10); + _50(out, rt.i8Shr(a, shift)); } else if (_52 === 10) { _50(out, ~a); } else if (_52 === 11) { @@ -790,11 +715,9 @@ export function i8Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.i8LeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.max(a, b); - _50(out, part2); + _50(out, rt.max(a, b)); } else if (_52 === 21) { - const part = rt.min(a, b); - _50(out, part); + _50(out, rt.min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, a === b ? 1 : 0); rt.byteVecPush(out, a < b ? 1 : 0); @@ -843,9 +766,7 @@ export function i16Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.i16 = _6[0]; const buf2: Uint8Array = rt.bytes(2); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.i16 = rt.i16FromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.i16, Uint8Array]; @@ -853,20 +774,15 @@ export function i16Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 16); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.i16Add(a, b); - _50(out, part16); + _50(out, rt.i16Add(a, b)); } else if (_52 === 1) { - const part15 = rt.i16Sub(a, b); - _50(out, part15); + _50(out, rt.i16Sub(a, b)); } else if (_52 === 2) { - const part14 = rt.i16Mul(a, b); - _50(out, part14); + _50(out, rt.i16Mul(a, b)); } else if (_52 === 3) { - const part13 = rt.i16Div(a, b); - _50(out, part13); + _50(out, rt.i16Div(a, b)); } else if (_52 === 4) { - const part12 = rt.i16Rem(a, b); - _50(out, part12); + _50(out, rt.i16Rem(a, b)); } else if (_52 === 5) { _50(out, a & b); } else if (_52 === 6) { @@ -874,11 +790,9 @@ export function i16Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, a ^ b); } else if (_52 === 8) { - const part11 = rt.i16Shl(a, shift); - _50(out, part11); + _50(out, rt.i16Shl(a, shift)); } else if (_52 === 9) { - const part10 = rt.i16Shr(a, shift); - _50(out, part10); + _50(out, rt.i16Shr(a, shift)); } else if (_52 === 10) { _50(out, ~a); } else if (_52 === 11) { @@ -907,11 +821,9 @@ export function i16Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.i16LeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.max(a, b); - _50(out, part2); + _50(out, rt.max(a, b)); } else if (_52 === 21) { - const part = rt.min(a, b); - _50(out, part); + _50(out, rt.min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, a === b ? 1 : 0); rt.byteVecPush(out, a < b ? 1 : 0); @@ -960,9 +872,7 @@ export function i32Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.i32 = _6[0]; const buf2: Uint8Array = rt.bytes(4); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.i32 = rt.i32FromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.i32, Uint8Array]; @@ -970,20 +880,15 @@ export function i32Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.i32Add(a, b); - _50(out, part16); + _50(out, rt.i32Add(a, b)); } else if (_52 === 1) { - const part15 = rt.i32Sub(a, b); - _50(out, part15); + _50(out, rt.i32Sub(a, b)); } else if (_52 === 2) { - const part14 = rt.i32Mul(a, b); - _50(out, part14); + _50(out, rt.i32Mul(a, b)); } else if (_52 === 3) { - const part13 = rt.i32Div(a, b); - _50(out, part13); + _50(out, rt.i32Div(a, b)); } else if (_52 === 4) { - const part12 = rt.i32Rem(a, b); - _50(out, part12); + _50(out, rt.i32Rem(a, b)); } else if (_52 === 5) { _50(out, a & b); } else if (_52 === 6) { @@ -991,11 +896,9 @@ export function i32Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, a ^ b); } else if (_52 === 8) { - const part11 = rt.i32Shl(a, shift); - _50(out, part11); + _50(out, rt.i32Shl(a, shift)); } else if (_52 === 9) { - const part10 = rt.i32Shr(a, shift); - _50(out, part10); + _50(out, rt.i32Shr(a, shift)); } else if (_52 === 10) { _50(out, ~a); } else if (_52 === 11) { @@ -1024,11 +927,9 @@ export function i32Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.i32LeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.max(a, b); - _50(out, part2); + _50(out, rt.max(a, b)); } else if (_52 === 21) { - const part = rt.min(a, b); - _50(out, part); + _50(out, rt.min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, a === b ? 1 : 0); rt.byteVecPush(out, a < b ? 1 : 0); @@ -1077,9 +978,7 @@ export function i64Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.i64 = _6[0]; const buf2: Uint8Array = rt.bytes(8); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.i64 = rt.i64FromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.i64, Uint8Array]; @@ -1087,20 +986,15 @@ export function i64Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 64); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.i64Add(a, b); - _50(out, part16); + _50(out, rt.i64Add(a, b)); } else if (_52 === 1) { - const part15 = rt.i64Sub(a, b); - _50(out, part15); + _50(out, rt.i64Sub(a, b)); } else if (_52 === 2) { - const part14 = rt.i64Mul(a, b); - _50(out, part14); + _50(out, rt.i64Mul(a, b)); } else if (_52 === 3) { - const part13 = rt.i64Div(a, b); - _50(out, part13); + _50(out, rt.i64Div(a, b)); } else if (_52 === 4) { - const part12 = rt.i64Rem(a, b); - _50(out, part12); + _50(out, rt.i64Rem(a, b)); } else if (_52 === 5) { _50(out, rt.i64And(a, b)); } else if (_52 === 6) { @@ -1108,11 +1002,9 @@ export function i64Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, rt.i64Xor(a, b)); } else if (_52 === 8) { - const part11 = rt.i64Shl(a, shift); - _50(out, part11); + _50(out, rt.i64Shl(a, shift)); } else if (_52 === 9) { - const part10 = rt.i64Shr(a, shift); - _50(out, part10); + _50(out, rt.i64Shr(a, shift)); } else if (_52 === 10) { _50(out, rt.i64Not(a)); } else if (_52 === 11) { @@ -1141,11 +1033,9 @@ export function i64Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.i64LeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.i64Max(a, b); - _50(out, part2); + _50(out, rt.i64Max(a, b)); } else if (_52 === 21) { - const part = rt.i64Min(a, b); - _50(out, part); + _50(out, rt.i64Min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, rt.i64Eq(a, b) ? 1 : 0); rt.byteVecPush(out, rt.i64Lt(a, b) ? 1 : 0); @@ -1194,9 +1084,7 @@ export function i128Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.i128 = _6[0]; const buf2: Uint8Array = rt.bytes(16); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.i128 = rt.i128FromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.i128, Uint8Array]; @@ -1204,20 +1092,15 @@ export function i128Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 128); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.i128Add(a, b); - _50(out, part16); + _50(out, rt.i128Add(a, b)); } else if (_52 === 1) { - const part15 = rt.i128Sub(a, b); - _50(out, part15); + _50(out, rt.i128Sub(a, b)); } else if (_52 === 2) { - const part14 = rt.i128Mul(a, b); - _50(out, part14); + _50(out, rt.i128Mul(a, b)); } else if (_52 === 3) { - const part13 = rt.i128Div(a, b); - _50(out, part13); + _50(out, rt.i128Div(a, b)); } else if (_52 === 4) { - const part12 = rt.i128Rem(a, b); - _50(out, part12); + _50(out, rt.i128Rem(a, b)); } else if (_52 === 5) { _50(out, rt.i128And(a, b)); } else if (_52 === 6) { @@ -1225,11 +1108,9 @@ export function i128Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, rt.i128Xor(a, b)); } else if (_52 === 8) { - const part11 = rt.i128Shl(a, shift); - _50(out, part11); + _50(out, rt.i128Shl(a, shift)); } else if (_52 === 9) { - const part10 = rt.i128Shr(a, shift); - _50(out, part10); + _50(out, rt.i128Shr(a, shift)); } else if (_52 === 10) { _50(out, rt.i128Not(a)); } else if (_52 === 11) { @@ -1258,11 +1139,9 @@ export function i128Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.i128LeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.i128Max(a, b); - _50(out, part2); + _50(out, rt.i128Max(a, b)); } else if (_52 === 21) { - const part = rt.i128Min(a, b); - _50(out, part); + _50(out, rt.i128Min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, rt.i128Eq(a, b) ? 1 : 0); rt.byteVecPush(out, rt.i128Lt(a, b) ? 1 : 0); @@ -1311,9 +1190,7 @@ export function isizeOp(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const a: rt.isize = _6[0]; const buf2: Uint8Array = rt.bytes(4); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); const _38: rt.isize = rt.isizeFromBeBytes(buf2); const slice2 = rt.sliceRange(data, n); [_38, rt.sliceRange(slice2, n2)] as [rt.isize, Uint8Array]; @@ -1321,20 +1198,15 @@ export function isizeOp(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { - const part16 = rt.isizeAdd(a, b); - _50(out, part16); + _50(out, rt.isizeAdd(a, b)); } else if (_52 === 1) { - const part15 = rt.isizeSub(a, b); - _50(out, part15); + _50(out, rt.isizeSub(a, b)); } else if (_52 === 2) { - const part14 = rt.isizeMul(a, b); - _50(out, part14); + _50(out, rt.isizeMul(a, b)); } else if (_52 === 3) { - const part13 = rt.isizeDiv(a, b); - _50(out, part13); + _50(out, rt.isizeDiv(a, b)); } else if (_52 === 4) { - const part12 = rt.isizeRem(a, b); - _50(out, part12); + _50(out, rt.isizeRem(a, b)); } else if (_52 === 5) { _50(out, a & b); } else if (_52 === 6) { @@ -1342,11 +1214,9 @@ export function isizeOp(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 7) { _50(out, a ^ b); } else if (_52 === 8) { - const part11 = rt.isizeShl(a, shift); - _50(out, part11); + _50(out, rt.isizeShl(a, shift)); } else if (_52 === 9) { - const part10 = rt.isizeShr(a, shift); - _50(out, part10); + _50(out, rt.isizeShr(a, shift)); } else if (_52 === 10) { _50(out, ~a); } else if (_52 === 11) { @@ -1375,11 +1245,9 @@ export function isizeOp(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_52 === 19) { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.isizeLeadingZeros(a))); } else if (_52 === 20) { - const part2 = rt.max(a, b); - _50(out, part2); + _50(out, rt.max(a, b)); } else if (_52 === 21) { - const part = rt.min(a, b); - _50(out, part); + _50(out, rt.min(a, b)); } else if (_52 === 22) { rt.byteVecPush(out, a === b ? 1 : 0); rt.byteVecPush(out, a < b ? 1 : 0); @@ -2129,12 +1997,8 @@ export function convert(data: Uint8Array, out: rt.ByteVec): void { const wide: rt.u64 = _5[0]; const buf2: Uint8Array = rt.bytes(4); const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); - const _31: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); - rt.sliceCopyFromSlice(_31, rt.sliceRange(slice, 0, n2)); - const _36: rt.i32 = rt.i32FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - const signed: rt.i32 = ([_36, rt.sliceRange(slice2, n2)] as [rt.i32, Uint8Array])[0]; + rt.sliceCopyFromSlice(rt.sliceRange(buf2, 0, n2), rt.sliceRange(rt.sliceRange(data, n), 0, n2)); + const signed: rt.i32 = ([rt.i32FromBeBytes(buf2), rt.sliceRange(rt.sliceRange(data, n), n2)] as [rt.i32, Uint8Array])[0]; rt.byteVecPush(out, rt.u8TryFrom(wide).ok ? 1 : 0); const _46: rt.Result = rt.u32TryFrom(wide); if (_46.ok) { diff --git a/ts/fixtures/lang/expected/iters.ts b/ts/fixtures/lang/expected/iters.ts index 685b5970f..8a3258a92 100644 --- a/ts/fixtures/lang/expected/iters.ts +++ b/ts/fixtures/lang/expected/iters.ts @@ -22,16 +22,10 @@ export function adaptors(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { }), (b11: rt.u8): boolean => { return rt.u8Rem(b11, 3) !== 0; })))); - const iterS: rt.u16[] = rt.iterToArray(rt.iterFilterMap(rt.iterSlice(data), (_217: rt.u8): rt.u16 | undefined => { + for (const _18 of rt.iterToArray(rt.iterFilterMap(rt.iterSlice(data), (_217: rt.u8): rt.u16 | undefined => { const b12: rt.u8 = _217; return rt.thenSome(b12 < 100, rt.u16Mul(b12 as rt.u16, 200)); - })); - let iterI: number = 0; - while (true) { - const _18: rt.u16 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_18 === rt.DONE) { - break; - } + }))) { rt.byteVecExtendFromSlice(out, rt.u16ToBeBytes(_18)); } } else { @@ -127,8 +121,7 @@ export function adaptors(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { })); const copies: Uint8Array[] = rt.iterToArray(rt.iterMap(rt.iterSlice(pairs), copy$u8s)); if (!((copies.length === 0))) { - const at = rt.idx(copies, 0); - copies[at][0] = 85; + copies[rt.idx(copies, 0)][0] = 85; } const iter4: rt.Iter = rt.iterChain(rt.iterSlice(pairs), rt.iterSlice(copies)); while (true) { @@ -157,21 +150,13 @@ export function adaptors(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { export function chunksByZero$ChunksByZero_u8s(self: Uint8Array): rt.ByteVec[] { const words: rt.ByteVec[] = []; let word: rt.ByteVec = new rt.ByteVec(); - const iterS: Uint8Array = self; - let iterI: number = 0; - while (true) { - const _6: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_6 === rt.DONE) { - break; - } - const b: rt.u8 = _6; + for (const b of self) { if (!(b === 0)) { rt.byteVecPush(word, b); } else { const taken = word; word = new rt.ByteVec(); - const _13: rt.ByteVec = taken; - words.push(_13); + words.push(taken); } } words.push(word); @@ -183,14 +168,12 @@ export function consumers(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void const log: rt.ByteVec = new rt.ByteVec(); const _5: rt.u8 = rt.u8Rem(kind, 6); if (_5 === 0) { - const _9: rt.Iter = rt.iterInspect(rt.iterSlice(data), (_228: rt.u8): void => { + rt.byteVecPush(out, rt.iterAny(rt.iterInspect(rt.iterSlice(data), (_228: rt.u8): void => { rt.byteVecPush(log, _228); - }); - rt.byteVecPush(out, rt.iterAny(_9, (_229: rt.u8): boolean => { + }), (_229: rt.u8): boolean => { return _229 > 240; }) ? 1 : 0); - const _17: rt.Iter = rt.iterSlice(data); - rt.byteVecPush(out, rt.iterAll(_17, (_230: rt.u8): boolean => { + rt.byteVecPush(out, rt.iterAll(rt.iterSlice(data), (_230: rt.u8): boolean => { return _230 !== 0; }) ? 1 : 0); rt.byteVecPush(out, rt.iterCount(rt.iterSlice(data)) & 0xff); @@ -198,22 +181,19 @@ export function consumers(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void return rt.u8Rem(_231, 2) === 0; })) & 0xff); } else if (_5 === 1) { - const _31: rt.Iter = rt.iterInspect(rt.iterSlice(data), (_220: rt.u8): void => { + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterFind(rt.iterInspect(rt.iterSlice(data), (_220: rt.u8): void => { rt.byteVecPush(log, _220); - }); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterFind(_31, (_221: rt.u8): boolean => { + }), (_221: rt.u8): boolean => { return rt.u8Rem(_221, 7) === 3; }), 255)); - const _40: rt.Iter = rt.iterSlice(data); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterFindMap(_40, (_222: rt.u8): rt.u8 | undefined => { + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterFindMap(rt.iterSlice(data), (_222: rt.u8): rt.u8 | undefined => { const b14: rt.u8 = _222; if (!(b14 > 80)) { return undefined; } return rt.u8CheckedMul(b14, 3); }), 0)); - const _45: rt.Iter = rt.iterSlice(data); - rt.byteVecPush(out, rt.optionMapOr(rt.iterPosition(_45, (_223: rt.u8): boolean => { + rt.byteVecPush(out, rt.optionMapOr(rt.iterPosition(rt.iterSlice(data), (_223: rt.u8): boolean => { return _223 === 64; }), 255, (p: rt.usize): rt.u8 => { return p & 0xff; @@ -269,23 +249,18 @@ export function consumers(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void return rt.u8Div(_219, 16); }), 238)); rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterLast(rt.iterSlice(data)), 221)); - const _140: rt.Iter = rt.iterSlice(data); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(_140, 3), 204)); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterSlice(data), 3), 204)); const it: rt.Iter = rt.iterSlice(data); - const _147: rt.Iter = rt.iterTake(it, rt.usizeRem(data.length, 3)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterToOption(_147.nthBackItem(1)), 187)); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterToOption(rt.iterTake(it, rt.usizeRem(data.length, 3)).nthBackItem(1)), 187)); rt.byteVecPush(out, it.len() & 0xff); - const _162: rt.Iter = rt.iterTake(it, rt.usizeRem(data.length, 5)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(_162, 2), 187)); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterTake(it, rt.usizeRem(data.length, 5)), 2), 187)); rt.byteVecPush(out, it.len() & 0xff); } else if (_5 === 3) { rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(rt.iterSum(rt.iterMap(rt.iterSlice(data), (_214: rt.u8): rt.u64 => { return rt.u64Mul(_214 as rt.u64, 1103823438081); }), rt.u64Add, 0))); rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.iterFold(rt.iterSlice(data), 0, (acc: rt.u32, _34: rt.u8): rt.u32 => { - const b8: rt.u8 = _34; - const _510: rt.u32 = (acc << 3) >>> 0; - return rt.u32WrappingAdd(_510, ((b8 as rt.u32) ^ acc) >>> 0); + return rt.u32WrappingAdd((acc << 3) >>> 0, ((_34 as rt.u32) ^ acc) >>> 0); }))); rt.iterForEach(rt.iterSlice(data), (_216: rt.u8): void => { rt.byteVecPush(log, rotateFree$RotateFree_u8(_216)); @@ -352,8 +327,7 @@ export function ranges(data: Uint8Array, out: rt.ByteVec): void { } rt.byteVecPush(out, _47); } - const _56: rt.Range = new rt.Range(a, b); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(_56, 5), 238)); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(new rt.Range(a, b), 5), 238)); rt.byteVecExtendFromSlice(out, rt.byteVecView(rt.iterToByteVec(new rt.RangeInclusive(rt.max(a, 250), 255, rt.u8Step)))); const inclusive: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.u8Step); rt.byteVecPush(out, rt.rangeInclusiveStart(inclusive)); @@ -367,19 +341,15 @@ export function ranges(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, rt.rangeInclusiveContains(near, 255) ? 1 : 0); rt.byteVecPush(out, rt.rangeInclusiveContains(near, 100) ? 1 : 0); const low: rt.RangeInclusive = new rt.RangeInclusive(0, b, rt.u8Step); - const _113: rt.usize = rt.usizeRem(a as rt.usize, 16); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterToOption(low.nthBackItem(_113)), 238)); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterToOption(low.nthBackItem(rt.usizeRem(a as rt.usize, 16))), 238)); rt.byteVecPush(out, rt.rangeInclusiveEnd(low)); - const _125: rt.u8 = rt.u8Div(b, 2); - rt.byteVecPush(out, rt.rangeInclusiveContains(low, _125) ? 1 : 0); + rt.byteVecPush(out, rt.rangeInclusiveContains(low, rt.u8Div(b, 2)) ? 1 : 0); const reversed: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.u8Step); - const _132: rt.Iter = rt.iterRev(reversed); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(_132, a as rt.usize), 238)); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterRev(reversed), a as rt.usize), 238)); rt.byteVecPush(out, rt.rangeInclusiveEnd(reversed)); rt.byteVecPush(out, rt.rangeInclusiveContains(reversed, a) ? 1 : 0); const counted: rt.Iter<[rt.usize, rt.u8]> = rt.iterEnumerate(new rt.RangeInclusive(a, b, rt.u8Step)); - const _152: rt.usize = rt.usizeDiv(b as rt.usize, 4); - const _149: [rt.usize, rt.u8] = rt.optionUnwrapOr(rt.iterNth(counted, _152), [221, 221] as [rt.usize, rt.u8]); + const _149: [rt.usize, rt.u8] = rt.optionUnwrapOr(rt.iterNth(counted, rt.usizeDiv(b as rt.usize, 4)), [221, 221] as [rt.usize, rt.u8]); const i3: rt.usize = _149[0]; const n: rt.u8 = _149[1]; rt.byteVecPush(out, i3 & 0xff); @@ -403,12 +373,9 @@ export function ranges(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(rt.iterSum(new rt.Range(0, a as rt.u64, rt.u64Step), rt.u64Add, 0))); const edge: rt.u64 = rt.u64Add(rt.u64Sub({ hi: 0x200000, lo: 0 } as rt.u64, 2), rt.u64Rem(a as rt.u64, 4)); const past: rt.Range = new rt.Range(edge, rt.u64Add(edge, 4), rt.u64Step); - const _223: rt.usize = rt.usizeRem(b as rt.usize, 3); - rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(rt.optionUnwrapOr(rt.iterNth(past, _223), 0))); + rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(rt.optionUnwrapOr(rt.iterNth(past, rt.usizeRem(b as rt.usize, 3)), 0))); rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(rt.optionUnwrapOr(rt.iterToOption(past.nextBack()), 0))); - const _240: rt.RangeInclusive = new rt.RangeInclusive(edge, rt.u64Add(edge, 3), rt.u64Step); - const _243: rt.usize = rt.usizeRem(b as rt.usize, 5); - rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(rt.optionUnwrapOr(rt.iterNth(_240, _243), 0))); + rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(rt.optionUnwrapOr(rt.iterNth(new rt.RangeInclusive(edge, rt.u64Add(edge, 3), rt.u64Step), rt.usizeRem(b as rt.usize, 5)), 0))); rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(rt.iterSum(rt.iterMap(new rt.RangeInclusive(rt.u64Sub({ hi: 0xffffffff, lo: 0xffffffff } as rt.u64, rt.u64Rem(a as rt.u64, 3)), { hi: 0xffffffff, lo: 0xffffffff } as rt.u64, rt.u64Step), (n4: rt.u64): rt.u64 => { return rt.u64Rem(n4, 7); }), rt.u64Add, 0))); @@ -416,13 +383,7 @@ export function ranges(data: Uint8Array, out: rt.ByteVec): void { return _24; }), 0))); rt.byteVecExtendFromSlice(out, rt.i64ToBeBytes(rt.optionUnwrapOr(rt.iterMin(new rt.Range(rt.i64Sub(rt.i64Neg({ hi: 0x200000, lo: 0 } as rt.i64), 1), rt.i64Add(rt.i64Neg({ hi: 0x200000, lo: 0 } as rt.i64), 1), rt.i64Step)), 0))); - const iterS: rt.u32[] = rt.iterToArray(rt.iterRev(rt.iterStepBy(new rt.Range(0, 48), 8))); - let iterI: number = 0; - while (true) { - const _295: rt.u32 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_295 === rt.DONE) { - break; - } + for (const _295 of rt.iterToArray(rt.iterRev(rt.iterStepBy(new rt.Range(0, 48), 8)))) { rt.byteVecPush(out, _295 & 0xff); } updates(a, b, data, out); @@ -468,8 +429,7 @@ export function updates(a: rt.u8, b: rt.u8, data: Uint8Array, out: rt.ByteVec): rt.byteVecPush(out, rt.sliceRange(data, 0).length & 0xff); rt.byteVecPush(out, rt.sliceRange(data, 0).length & 0xff); const copied: rt.ByteVec = rt.sliceToByteVec(data); - const _76: Uint8Array = rt.byteVecView(copied); - rt.sliceCopyWithin(_76, 0, to, 0); + rt.sliceCopyWithin(rt.byteVecView(copied), 0, to, 0); rt.byteVecExtendFromSlice(out, rt.byteVecView(copied)); } @@ -551,8 +511,7 @@ export function options(data: Uint8Array, out: rt.ByteVec): void { /** The second item of an iterator of options, through `?`, which tests for its end. */ export function second$Map_Iter_u8_options_closure0(items: rt.Iter): rt.u8 | undefined { - const _2: rt.u8 | undefined | rt.Done = items.next(); - if (_2 !== rt.DONE) { + if (items.next() !== rt.DONE) { const _7: rt.u8 | undefined | rt.Done = items.next(); if (_7 !== rt.DONE) { return rt.optionUnwrapOr(_7, 171); diff --git a/ts/fixtures/lang/expected/keys.ts b/ts/fixtures/lang/expected/keys.ts index b5eef3384..2bf4a266e 100644 --- a/ts/fixtures/lang/expected/keys.ts +++ b/ts/fixtures/lang/expected/keys.ts @@ -253,16 +253,13 @@ export function options(data: Uint8Array, out: rt.ByteVec): void { r = _229; s2 = _234; rt.byteVecPush(out, (!rt.eqOption(Picky.eq$PartialEq)(g, h) ? 1 : 0) | (((!rt.eqTuple([rt.eqOption(Picky.eq$PartialEq), rt.same])(j, k) ? 1 : 0) << 1) & 0xff) | (((!rt.eqArc(rt.eqOption(Picky.eq$PartialEq))(r, s2) ? 1 : 0) << 2) & 0xff)); - const _261: rt.u8 = rt.u8Rem(c, 3); - const _264: boolean = rt.u8Rem(d, 2) === 0; - const key: [rt.u8, Horizon.Horizon] = [_261, { exclude: a, local: _264 }]; + const key: [rt.u8, Horizon.Horizon] = [rt.u8Rem(c, 3), { exclude: a, local: rt.u8Rem(d, 2) === 0 }]; const _269: rt.u8 | undefined = rt.hashInsert(hashed, key, i & 0xff); unwind = 133; rt.byteVecPush(out, rt.optionUnwrapOr(_269, 204)); rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeInsert(sorted, key, i & 0xff), 204)); const _281: [Way.Way | undefined, boolean] = [way(c), c < 128]; - const _284: rt.u8 = i & 0xff; - rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashInsert(ways, _281, _284), 204)); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashInsert(ways, _281, i & 0xff), 204)); const _291: [Way.Way | undefined, boolean] = [way(d), d < 128]; rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashGet(ways, _291), 221)); rt.byteVecPush(out, rt.hashLen(ways) & 0xff); @@ -363,8 +360,7 @@ export function arcs(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, (rt.eqArc(rt.same, true)(a.text, b.text) ? 1 : 0) | (((Name.eq$PartialEq(a, b) ? 1 : 0) << 1) & 0xff) | (((rt.eqArc(rt.same, true)(rt.ordMax(a.text, b.text, rt.cmpArc(rt.cmpStr)), b.text) ? 1 : 0) << 2) & 0xff)); rt.byteVecPush(out, (rt.u64Eq(hashOf$Arc_str(a.text), hashOf$Arc_str(b.text)) ? 1 : 0) | (((rt.u64Eq(hashOf$Name(a), hashOf$Name(b)) ? 1 : 0) << 1) & 0xff)); const text: string = a.text.value; - const _102: string = b.text.value; - rt.byteVecPush(out, text === _102 ? 1 : 0); + rt.byteVecPush(out, text === b.text.value ? 1 : 0); rt.idx(data, i); const _106: rt.usize = rt.usizeRem(data[i] as rt.usize, ["", "a", "ab", "", "￿", "𐀀"].length); if (!(_106 < 6)) { @@ -514,8 +510,7 @@ export function places(data: Uint8Array, out: rt.ByteVec): void { const place6 = rt.entryGetMut(_35); place6.v = rt.usizeAdd(place6.v, 7); } else { - const e: rt.Entry = _35; - const place5 = rt.entryGetMut(e); + const place5 = rt.entryGetMut(_35); place5.v = rt.usizeMul(place5.v, 3); } } else if (_18 === 3) { @@ -536,8 +531,7 @@ export function places(data: Uint8Array, out: rt.ByteVec): void { const place = rt.optionUnwrap(rt.btreeGetMut(counts, k)); place.v = rt.usizeAdd(place.v, 1); } - const _82: rt.u8 = rt.u8Rem(b, 7); - const place9 = rt.entryOrInsertMut(rt.entry(wide, _82), 4503599627370496); + const place9 = rt.entryOrInsertMut(rt.entry(wide, rt.u8Rem(b, 7)), 4503599627370496); place9.v = rt.u64WrappingAdd(rt.u64WrappingAdd(place9.v, rt.u64Shr(place9.v, 1)), b as rt.u64); const _98: Hop.Hop = { _0: rt.u64Rem(b as rt.u64, 6) }; const place10 = rt.entryOrInsertWithMut(rt.entry(hops, _98), (): rt.u16 => { @@ -556,8 +550,7 @@ export function places(data: Uint8Array, out: rt.ByteVec): void { const place13 = rt.entryGetMut(_114); place13.v = place13.v | 1; } else { - const e4: rt.Entry = _114; - const place12 = rt.entryGetMut(e4); + const place12 = rt.entryGetMut(_114); place12.v = rt.u16Sub(place12.v, 4096); } } else { @@ -579,8 +572,7 @@ export function places(data: Uint8Array, out: rt.ByteVec): void { const _159: rt.usize = rt.usizeRem(j, data.length); rt.idx(data, _159); const b2: rt.u8 = data[_159]; - const _167: rt.u16 = rt.u16Mul(j & 0xffff, 37) ^ b2 as rt.u16; - const place15 = rt.entryOrInsertMut(rt.entry(tree, _167), j & 0xffff); + const place15 = rt.entryOrInsertMut(rt.entry(tree, rt.u16Mul(j & 0xffff, 37) ^ b2 as rt.u16), j & 0xffff); place15.v = rt.u16WrappingAdd(place15.v, b2 as rt.u16); } const iter3: rt.Iter<[rt.u16, rt.u16]> = rt.btreeIter(tree); @@ -606,10 +598,9 @@ export function places(data: Uint8Array, out: rt.ByteVec): void { const place18 = rt.entryOrInsertWithMut(rt.entry(counts, 0), (): rt.usize => { return 0; }); - const bump: () => void = (): void => { + ((): void => { place18.v = rt.usizeAdd(place18.v, 1); - }; - bump(); + })(); const spare: rt.usize[] = [data.length, 8]; const place19 = rt.entryOrInsertMut(rt.entry(counts, 1), 3); const swapped = place19.v; diff --git a/ts/fixtures/lang/expected/shapes.Shape.ts b/ts/fixtures/lang/expected/shapes.Shape.ts index 5fd6e2a69..dd07eb797 100644 --- a/ts/fixtures/lang/expected/shapes.Shape.ts +++ b/ts/fixtures/lang/expected/shapes.Shape.ts @@ -42,9 +42,7 @@ export function area$Area(self: Shape): rt.u64 { if (self.tag === "Line") { return 0; } - const width: rt.u16 = self.width; - const height: rt.u16 = self.height; - return rt.u64Mul(width as rt.u64, height as rt.u64); + return rt.u64Mul(self.width as rt.u64, self.height as rt.u64); } //# sourceMappingURL=shapes.Shape.ts.map diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 77a72187c..8f8e5f137 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -90,8 +90,7 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { let _246!: rt.u8; const p: Point.Point = Point.new(rt.optionUnwrapOr(rt.sliceFirst(data), 0) as rt.i32, 7); const q: Point.Point = copy$Point(p); - const _9: rt.i32 = rt.i32Add(q.x, 100); - q.x = _9; + q.x = rt.i32Add(q.x, 100); Point.bump(q); const r: Point.Point = Point.shift(p, 5); const pair: [Point.Point, rt.u8] = [copy$Point(p), 3]; @@ -104,18 +103,8 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { }); grid[1].x = 9; const row: Point.Point[] = copy$Points(grid); - const _20: Point.Point = copy$Point(q); - grid[2] = copy$Point(_20); - const _25: rt.i32 = p.x; - const _26: rt.i32 = p.y; - const _27: rt.i32 = q.x; - const _28: rt.i32 = q.y; - const _29: rt.i32 = r.x; - const _30: rt.i32 = saved[0].y; - const _31: rt.i32 = pair[0].y; - const _32: rt.i32 = row[1].x; - const _35: rt.i32 = row[2].x; - const iter: rt.Iter = rt.iterSlice([_25, _26, _27, _28, _29, _30, _31, _32, _35, grid[2].x]); + grid[2] = copy$Point(copy$Point(q)); + const iter: rt.Iter = rt.iterSlice([p.x, p.y, q.x, q.y, r.x, saved[0].y, pair[0].y, row[1].x, row[2].x, grid[2].x]); while (true) { const _42: rt.i32 | rt.Done = iter.next(); if (_42 === rt.DONE) { @@ -134,17 +123,10 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { const _66: Point.Point = Point.new(5, 6); const old2 = a; a = copy$Point(_66); - const old: Point.Point = old2; - const _71: rt.u8 = a.x & 0xff; - const _73: rt.u8 = b.x & 0xff; - rt.byteVecExtendFromSlice(out, Uint8Array.of(_71, _73, old.x & 0xff)); + rt.byteVecExtendFromSlice(out, Uint8Array.of(a.x & 0xff, b.x & 0xff, old2.x & 0xff)); const boxed: Moved.Moved = { _0: data.length & 0xff, _1: 0 }; - const _81: rt.u16 = rt.u16Add(boxed._1, 1); - const _257: Moved.Moved = boxed; - _257._1 = _81; - const _83: rt.u16 = rt.u16Add(boxed._1, 2); - const _254: Moved.Moved = boxed; - _254._1 = _83; + boxed._1 = rt.u16Add(boxed._1, 1); + boxed._1 = rt.u16Add(boxed._1, 2); rt.byteVecExtendFromSlice(out, Uint8Array.of(boxed._0)); rt.byteVecExtendFromSlice(out, rt.u16ToBeBytes(boxed._1)); let n: rt.u32 = data.length as rt.u32; @@ -160,8 +142,7 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { const source: Uint8Array = Uint8Array.of(data.length & 0xff); const returned: Uint8Array = same(copy$u8s(source)); source[0] = 9; - const _145: rt.u8 = returned[0]; - rt.byteVecExtendFromSlice(out, Uint8Array.of(_145, source[0])); + rt.byteVecExtendFromSlice(out, Uint8Array.of(returned[0], source[0])); rt.byteVecPush(out, copyThenWrite([data.length & 0xff, 0] as [rt.u8, rt.u8])); const marked: boolean = mark(out, 1) === 0; mark(out, 2); @@ -205,10 +186,7 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { _211 = Uint8Array.of(1, from.x & 0xff, from.y & 0xff); } else { const corner: Point.Point = shape2.corner; - const width: rt.u16 = shape2.width; - const _220: rt.u8 = corner.x & 0xff; - const _222: rt.u8 = corner.y & 0xff; - _211 = Uint8Array.of(_220, _222, width & 0xff); + _211 = Uint8Array.of(corner.x & 0xff, corner.y & 0xff, shape2.width & 0xff); } rt.byteVecExtendFromSlice(out, _211); } @@ -219,8 +197,7 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { } const polled_: rt.Poll = copy$Poll_u8s(poll); if (poll !== rt.Pending) { - const bytes: Uint8Array = poll; - bytes[0] = 9; + poll[0] = 9; } const iter3: rt.Iter> = rt.iterSlice([polled_, copy$Poll_u8s(poll)]); while (true) { @@ -230,8 +207,7 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { } const poll2: rt.Poll = _241; if (poll2 !== rt.Pending) { - const bytes2: Uint8Array = poll2; - _246 = bytes2[0]; + _246 = poll2[0]; } else { _246 = 255; } @@ -323,15 +299,9 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { bump(copy5.slot); rt.byteVecExtendFromSlice(out, Uint8Array.of(a, copy5.n)); rt.byteVecPush(out, lensBumped(lens)); - const iterS: Lens.Lens[] = Array.from({ length: 2 }, (): Lens.Lens => { + for (const _104 of Array.from({ length: 2 }, (): Lens.Lens => { return copy$Lens(lens); - }).map(copy$Lens); - let iterI: number = 0; - while (true) { - const _104: Lens.Lens | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_104 === rt.DONE) { - break; - } + }).map(copy$Lens)) { bump(_104.slot); } const lenses: Lens.Lens[] = []; @@ -368,8 +338,7 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { const read: rt.i32 = movedThenRead(copy$Point(source.at), source); const by: rt.i32 = movedBy(copy$Point(source.at), { held: source }); const part: rt.i32 = partMovedThenRead(copy$Held(source), source.at); - const _172: rt.u8 = kept.at.x & 0xff; - rt.byteVecExtendFromSlice(out, Uint8Array.of(_172, read & 0xff, by & 0xff, part & 0xff, source.at.x & 0xff)); + rt.byteVecExtendFromSlice(out, Uint8Array.of(kept.at.x & 0xff, read & 0xff, by & 0xff, part & 0xff, source.at.x & 0xff)); unwind = 102; const bytes: Uint8Array = Uint8Array.of(a, 1); rt.byteVecPush(out, unsizedCopy(bytes)); @@ -392,8 +361,7 @@ export function hold(at: Point.Point): Held.Held { /** `copy.x`, read after `held` moves right by one, which a copy of its point doesn't see. */ export function movedThenRead(copy: Point.Point, held: Held.Held): rt.i32 { - const _3: rt.i32 = rt.i32Add(held.at.x, 1); - held.at.x = _3; + held.at.x = rt.i32Add(held.at.x, 1); return copy.x; } @@ -419,10 +387,8 @@ export function unsizedCopy(src: Uint8Array): rt.u8 { /** `copy.x`, read after `by` moves what it holds right by one. */ export function movedBy(copy: Point.Point, by: Mover.Mover): rt.i32 { - const _3: rt.i32 = rt.i32Add(by.held.at.y, 1); - by.held.at.y = _3; - const _4: rt.i32 = rt.i32Add(by.held.at.x, 1); - by.held.at.x = _4; + by.held.at.y = rt.i32Add(by.held.at.y, 1); + by.held.at.x = rt.i32Add(by.held.at.x, 1); return copy.x; } @@ -483,25 +449,20 @@ export function order(data: Uint8Array, out: rt.ByteVec): void { const _5: rt.u16 = mark(out, at(0)) & 0xffff; const _10: rt.u16 = mark(out, at(1)) & 0xffff; const _16: rt.i32 = mark(out, 2) | 0; - const _18: rt.i32 = mark(out, 3) | 0; - const rect: Shape.Shape = { tag: "Rect", corner: { x: _18, y: _16 }, width: _10, height: _5 }; + const rect: Shape.Shape = { tag: "Rect", corner: { x: mark(out, 3) | 0, y: _16 }, width: _10, height: _5 }; const _21: Point.Point = Point.new(mark(out, 4) | 0, 0); - const _24: Point.Point = Point.new(mark(out, 5) | 0, 0); - const line: Shape.Shape = { tag: "Line", _0: _24, _1: _21 }; + const line: Shape.Shape = { tag: "Line", _0: Point.new(mark(out, 5) | 0, 0), _1: _21 }; const _28: rt.i64 = mark(out, 6) as rt.i64; - const _30: rt.u8 = mark(out, 7) & 0xff; - const pair: Pair.Pair = { _0: _30, _1: _28 }; + const pair: Pair.Pair = { _0: mark(out, 7) & 0xff, _1: _28 }; const n: Uint8Array = Uint8Array.of(at(2)); const _37: rt.i32 = n[0] as rt.i32; - const _41: rt.i32 = increment(n) as rt.i32; - const read: Point.Point = { x: _41, y: _37 }; + const read: Point.Point = { x: increment(n) as rt.i32, y: _37 }; const base: Moved.Moved = { _0: at(4), _1: 0 }; const _49: rt.u16 = reset(base); const updated: Moved.Moved = { _0: base._0, _1: _49 }; if (rt.u8Rem(at(3), 2) === 0) { const _57: rt.u16 = mark(out, 8) & 0xffff; - const _59: Point.Point = Point.new(0, mark(out, 9) | 0); - taken = { tag: "Rect", corner: _59, width: _57, height: 1 } as Shape.Shape; + taken = { tag: "Rect", corner: Point.new(0, mark(out, 9) | 0), width: _57, height: 1 } as Shape.Shape; } else { taken = { tag: "Dot" } as Shape.Shape; } @@ -518,8 +479,7 @@ export function order(data: Uint8Array, out: rt.ByteVec): void { const len: rt.usize = data.length; const _83: Uint8Array = logged(data, out); const _85: rt.usize = rt.min(mark(out, 14), len); - const _87: rt.usize = rt.usizeDiv(rt.min(mark(out, 15), len), 2); - const _82: Uint8Array = rt.sliceRange(_83, _87, _85); + const _82: Uint8Array = rt.sliceRange(_83, rt.usizeDiv(rt.min(mark(out, 15), len), 2), _85); const _102: Shape.Shape = taken; const _103: rt.usize = sum; const args2: rt.Fmt[] = [(f: rt.Formatter) => Shape.fmt$Debug(rect, f), (f: rt.Formatter) => Shape.fmt$Debug(line, f), (f: rt.Formatter) => Pair.fmt$Debug(pair, f), (f: rt.Formatter) => Point.fmt$Debug(read, f), (f: rt.Formatter) => Moved.fmt$Debug(updated, f), (f: rt.Formatter) => Shape.fmt$Debug(_102, f), (f: rt.Formatter) => rt.usizeDisplay(_64, f), (f: rt.Formatter) => rt.usizeDisplay(_63, f), (f: rt.Formatter) => rt.usizeDisplay(_103, f), (f: rt.Formatter) => rt.fmtList(_82, f, rt.u8Display)]; @@ -539,8 +499,7 @@ export function indexed(data: Uint8Array, out: rt.ByteVec): void { const _7: rt.ByteVec = listed(out, at(0)); rt.byteVecPush(out, 225); const slice = rt.byteVecView(_7); - const at2 = rt.idx(slice, 1); - const first: rt.u8 = slice[at2]; + const first: rt.u8 = slice[rt.idx(slice, 1)]; const bytes: Uint8Array = Uint8Array.of(at(1), at(2), at(3), 4); const _23: Uint8Array = loggedMut(bytes, out); rt.byteVecPush(out, 227); @@ -564,8 +523,7 @@ export function indexed(data: Uint8Array, out: rt.ByteVec): void { const _58: rt.u8 = n; n = rt.u8WrappingAdd(n, 1); slots[0] = rt.u8Add(slots[0], _58); - const _68: rt.u8 = f(1); - rt.byteVecExtendFromSlice(out, Uint8Array.of(first, second, called, _68, slots[0], n)); + rt.byteVecExtendFromSlice(out, Uint8Array.of(first, second, called, f(1), slots[0], n)); rt.byteVecExtendFromSlice(out, bytes); } @@ -597,8 +555,7 @@ export function logged(data: Uint8Array, out: rt.ByteVec): Uint8Array { /** `n`'s byte, incremented. */ export function increment(n: Uint8Array): rt.u8 { - const _2: rt.u8 = rt.u8WrappingAdd(n[0], 1); - n[0] = _2; + n[0] = rt.u8WrappingAdd(n[0], 1); return n[0]; } @@ -612,14 +569,7 @@ export function reset(m: Moved.Moved): rt.u16 { export function discriminants(data: Uint8Array, out: rt.ByteVec): void { let wide!: Wide.Wide; let signed!: Signed.Signed; - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _5: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_5 === rt.DONE) { - break; - } - const b: rt.u8 = _5; + for (const b of data) { const _10: rt.u8 = rt.u8Rem(b, 3); if (_10 === 0) { wide = "Low" as Wide.Wide; @@ -714,9 +664,7 @@ export function loops(data: Uint8Array, out: rt.ByteVec): void { if (found === undefined) { rt.byteVecPush(out, 255); } else { - const i2: rt.usize = found[0]; - const j2: rt.usize = found[1]; - rt.byteVecExtendFromSlice(out, Uint8Array.of(i2 & 0xff, j2 & 0xff)); + rt.byteVecExtendFromSlice(out, Uint8Array.of(found[0] & 0xff, found[1] & 0xff)); } let n: rt.u64 = data.length as rt.u64; b6: { @@ -737,11 +685,7 @@ export function loops(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, steps); let count: rt.u8 = 0; const iter3: rt.RangeInclusive = new rt.RangeInclusive(0, 3, rt.u8Step); - while (true) { - const _84: rt.u8 | rt.Done = iter3.next(); - if (_84 === rt.DONE) { - break; - } + while (iter3.next() !== rt.DONE) { count = rt.u8Add(count, 1); } let i3: rt.i8 = 10; @@ -1047,14 +991,7 @@ export function branchLoops(data: Uint8Array, out: rt.ByteVec): void { export function returnedLoop(data: Uint8Array): rt.u8 { let i: rt.usize = 0; while (!(i >= data.length)) { - const iterS: Uint8Array = rt.sliceRange(data, i); - let iterI: number = 0; - while (true) { - const _11: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_11 === rt.DONE) { - break; - } - const b: rt.u8 = _11; + for (const b of rt.sliceRange(data, i)) { if (!(b === 0)) { if (b > 240) { return b ^ (i & 0xff); @@ -1222,13 +1159,7 @@ export function patterns(data: Uint8Array, out: rt.ByteVec): void { } else { rt.byteVecPush(out, 0); } - const iterS: Uint8Array = rt.sliceRange(data, 0, rt.min(data.length, 4)); - let iterI: number = 0; - while (true) { - const _33: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_33 === rt.DONE) { - break; - } + for (const _33 of rt.sliceRange(data, 0, rt.min(data.length, 4))) { b3: { const b: rt.u8 = _33; if (b === 0) { @@ -1283,14 +1214,10 @@ export function patterns(data: Uint8Array, out: rt.ByteVec): void { } if (shape_.width !== 0) { if (!(shape_.corner.x > 0)) { - const width2: rt.u16 = shape_.width; - const height: rt.u16 = shape_.height; - area = rt.i64Neg(rt.i64Mul(width2 as rt.i64, height as rt.i64)); + area = rt.i64Neg(rt.i64Mul(shape_.width as rt.i64, shape_.height as rt.i64)); break b8; } - const x: rt.i32 = shape_.corner.x; - const _74: rt.i64 = shape_.width as rt.i64; - area = rt.i64Mul(_74, x as rt.i64); + area = rt.i64Mul(shape_.width as rt.i64, shape_.corner.x as rt.i64); break b8; } } @@ -1315,8 +1242,7 @@ export function patterns(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(rt.u64Add(total$Shape([shape_, { tag: "Dot" } as Shape.Shape], out), total$Meters([{ _0: 3 }, { _0: { hi: 0xffffffff, lo: 0xffffffff } as rt.u64 }], out)))); const parsed: rt.Result = rt.Ok(data.length & 0xff); const a2: rt.u8 = (parsed as { ok: true; value: rt.u8 }).value; - const b3: rt.u8 = (parsed as { ok: true; value: rt.u8 }).value; - rt.byteVecExtendFromSlice(out, Uint8Array.of(a2, b3, (parsed as { ok: true; value: rt.u8 }).value, early(a2))); + rt.byteVecExtendFromSlice(out, Uint8Array.of(a2, (parsed as { ok: true; value: rt.u8 }).value, (parsed as { ok: true; value: rt.u8 }).value, early(a2))); const arg = ([parsed] as [rt.Result])[0]; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtResult(arg, f, rt.u8Display, (value: Void.Void, f: rt.Formatter) => Void.fmt$Debug(value, f))]; rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0]]))); @@ -1333,13 +1259,7 @@ export function closures(data: Uint8Array, out: rt.ByteVec): void { const add: (a0: rt.u8) => void = (v: rt.u8): void => { sum = rt.u32Add(sum, v as rt.u32); }; - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _8: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_8 === rt.DONE) { - break; - } + for (const _8 of data) { add(_8); } rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(sum)); @@ -1358,24 +1278,12 @@ export function closures(data: Uint8Array, out: rt.ByteVec): void { overwrite(whole); rt.byteVecPush(out, whole[0]); const parsed: Array = []; - const iterS2: Uint8Array = data; - let iterI2: number = 0; - while (true) { - const _53: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_53 === rt.DONE) { - break; - } + for (const _53 of data) { const _59: Dir.Dir | undefined = dir(_53); parsed.push(_59); } const tags: rt.ByteVec = new rt.ByteVec(); - const iterS3: Array = parsed; - let iterI3: number = 0; - while (true) { - const _64: Dir.Dir | undefined | rt.Done = iterI3 < iterS3.length ? iterS3[iterI3++] : rt.DONE; - if (_64 === rt.DONE) { - break; - } + for (const _64 of parsed) { const _70: rt.u8 = rt.optionUnwrapOr(rt.optionMap(_64, from$From_Dir_u8), 0); rt.byteVecPush(tags, _70); } @@ -1384,10 +1292,9 @@ export function closures(data: Uint8Array, out: rt.ByteVec): void { /** Replaces `a` whole from a closure. */ export function overwrite(a: Uint8Array): void { - const write: () => void = (): void => { + ((): void => { a.set(Uint8Array.of(9)); - }; - write(); + })(); } export function apply$closures_closure1(f: (a0: rt.u32) => rt.u32, v: rt.u32): rt.u32 { @@ -1424,8 +1331,7 @@ export function library(data: Uint8Array, out: rt.ByteVec): void { if (_132.ok) { return rt.Ok(_132.value); } - const residual: rt.Result = _132; - return rt.Err(from$From_Dir_u8((residual as { ok: false; error: Dir.Dir }).error)); + return rt.Err(from$From_Dir_u8((_132 as { ok: false; error: Dir.Dir }).error)); }; const a: rt.u8 = rt.optionUnwrapOr(rt.sliceFirst(data), 0); const b: rt.u8 = rt.optionUnwrapOr(rt.sliceGet(data, 1), 0); @@ -1505,14 +1411,7 @@ export function flows(data: Uint8Array, out: rt.ByteVec): void { let option!: rt.u8 | undefined; let _113!: boolean; let total: rt.u16 = 0; - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _7: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_7 === rt.DONE) { - break; - } - const x: rt.u8 = _7; + for (const x of data) { const flow: rt.Result = step(total, x); rt.byteVecExtendFromSlice(out, Uint8Array.of(!flow.ok ? 1 : 0, flow.ok ? 1 : 0)); if (flow.ok) { @@ -1575,14 +1474,7 @@ export function flows(data: Uint8Array, out: rt.ByteVec): void { } } const slot: rt.Mutex = new rt.Mutex(undefined); - const iterS2: Uint8Array = data; - let iterI2: number = 0; - while (true) { - const _106: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_106 === rt.DONE) { - break; - } - const x2: rt.u8 = _106; + for (const x2 of data) { const held: rt.Mutex = slot; const _114: rt.u8 | undefined = held.value; b12: { diff --git a/ts/fixtures/task/expected/kio.Consumer.ts b/ts/fixtures/task/expected/kio.Consumer.ts index f50a51324..24ea321e7 100644 --- a/ts/fixtures/task/expected/kio.Consumer.ts +++ b/ts/fixtures/task/expected/kio.Consumer.ts @@ -34,9 +34,7 @@ export function pollRecv(self: Consumer, waiter: Waiter.Waiter): rt.Poll = self.state.value; state.value.queue.push(value); - const waiters: WaiterList.WaiterList = WaiterList.take(state.value.waiters); - WaiterList.wake(waiters); + WaiterList.wake(WaiterList.take(state.value.waiters)); } export function consume(self: Producer): Consumer.Consumer { @@ -36,8 +35,7 @@ export function consume(self: Producer): Consumer.Consumer { } export function clone$Clone(self: Producer): Producer { - const _4: rt.Mutex = self.state.value; - const _2: State.State = _4.value; + const _2: State.State = self.state.value.value; _2.producers = rt.usizeAdd(_2.producers, 1); return new Producer({ state: rt.arcClone(self.state) }); } @@ -48,8 +46,7 @@ export function drop$Drop(self: Producer): void { _7.producers = rt.usizeSub(_7.producers, 1); if (!(state.value.producers > 0)) { state.value.closed = true; - const waiters: WaiterList.WaiterList = WaiterList.take(state.value.waiters); - WaiterList.wake(waiters); + WaiterList.wake(WaiterList.take(state.value.waiters)); } } diff --git a/ts/fixtures/task/expected/kio.Waiter.ts b/ts/fixtures/task/expected/kio.Waiter.ts index 50e0b270d..c69a77ef6 100644 --- a/ts/fixtures/task/expected/kio.Waiter.ts +++ b/ts/fixtures/task/expected/kio.Waiter.ts @@ -24,8 +24,7 @@ function new_(waker: rt.Waker): Waiter { try { unwind = 4; const shared: rt.Arc = new rt.Arc(waker.clone()); - const _5: rt.Waker = waker; - return new Waiter({ waker: _5, shared }); + return new Waiter({ waker, shared }); } catch (e) { if (unwind === 0) { throw e; diff --git a/ts/fixtures/task/expected/kio.WaiterList.ts b/ts/fixtures/task/expected/kio.WaiterList.ts index 85ff1edb9..92963af63 100644 --- a/ts/fixtures/task/expected/kio.WaiterList.ts +++ b/ts/fixtures/task/expected/kio.WaiterList.ts @@ -16,30 +16,19 @@ function new_(): WaiterList { export function register(self: WaiterList, waiter: Waiter.Waiter): void { const weak: rt.Weak = new rt.Weak(waiter.shared); - const iterS: rt.Weak[] = self.entries; - let iterI: number = 0; b1: { - while (true) { - const _8: rt.Weak | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_8 === rt.DONE) { - break; - } + for (const _8 of self.entries) { if (_8.arc === weak.arc) { break b1; } } let probes: rt.usize = rt.min(self.entries.length, 2); while (probes > 0) { - const _23: rt.usize = self.cursor; - const at = rt.idx(self.entries, _23); - if (!(self.entries[at].arc.strong === 0)) { + if (!(self.entries[rt.idx(self.entries, self.cursor)].arc.strong === 0)) { self.cursor = rt.usizeRem(rt.usizeAdd(self.cursor, 1), self.entries.length); probes = rt.usizeSub(probes, 1); } else { - const _24: rt.Weak = weak; - const _27: rt.usize = self.cursor; - const at2 = rt.idx(self.entries, _27); - self.entries[at2] = _24; + self.entries[rt.idx(self.entries, self.cursor)] = weak; break b1; } } @@ -47,20 +36,12 @@ export function register(self: WaiterList, waiter: Waiter.Waiter): void { const live: rt.Weak[] = []; const taken = self.entries; self.entries = []; - const iterS2: rt.Weak[] = taken; - let iterI2: number = 0; - while (true) { - const _43: rt.Weak | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_43 === rt.DONE) { - break; - } - const entry: rt.Weak = _43; + for (const entry of taken) { if (entry.arc.strong > 0) { live.push(entry); } } - const _53: rt.Weak[] = live; - self.entries = _53; + self.entries = live; self.cursor = 0; } self.entries.push(weak); @@ -83,13 +64,7 @@ export function wake(self: WaiterList): void { self.cursor = 0; const taken = self.entries; self.entries = []; - const iterS: rt.Weak[] = taken; - let iterI: number = 0; - while (true) { - const _6: rt.Weak | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_6 === rt.DONE) { - break; - } + for (const _6 of taken) { const _10: rt.Arc | undefined = rt.weakUpgrade(_6); if (_10 !== undefined) { unwind = 15; diff --git a/ts/fixtures/task/expected/log.Log.ts b/ts/fixtures/task/expected/log.Log.ts index c662d6fcf..2c43bfcdf 100644 --- a/ts/fixtures/task/expected/log.Log.ts +++ b/ts/fixtures/task/expected/log.Log.ts @@ -25,9 +25,7 @@ function new_(): Log { /** Append one event. */ export function note(self: Log, event: string): void { - const _6: rt.Mutex = self._0.value; - const _4: string[] = _6.value; - _4.push(event); + self._0.value.value.push(event); } /** Every event so far, one per line. */ diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 7d889f54b..35e740b2c 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -423,8 +423,7 @@ export class blocksFuture { unwind = 142; this.#saved$6 = true; rt.drop(new blocksFuture$2(this.#first)); - const _18: rt.u32 = rt.u32Rem(this.#guard$2.id, 5); - turns(this.#guard$2.log, _18); + turns(this.#guard$2.log, rt.u32Rem(this.#guard$2.id, 5)); temporaries(this.#guard$2.log, this.#guard$2.id); unwind = 130; this.#saved = Guard.new(rt.u32Add(this.#guard$2.id, 900), Log.clone$Clone(this.#guard$2.log)); @@ -490,14 +489,12 @@ export class blocksFuture { const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(arg, f)]; const _78: string = rt.fmtFormat(["slot after ", args2[0]]); unwind = 117; - const _76: string = _78; - Guard.note(this.#slots[0], _76); + Guard.note(this.#slots[0], _78); unwind = 137; this.#tally = { n: this.#guard$2.id }; this.#saved$9 = true; seen = new blocksFuture$3(copy$Tally(this.#tally)); - const _89: rt.u32 = rt.u32Add(this.#tally.n, 1000); - this.#tally.n = _89; + this.#tally.n = rt.u32Add(this.#tally.n, 1000); this.#saved$3 = this.#guard$2; this.#saved$4 = this.#tally.n; this.#saved$9 = false; @@ -517,8 +514,7 @@ export class blocksFuture { const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f), (f: rt.Formatter) => rt.u32Display(_98, f)]; const _93: string = rt.fmtFormat(["tally ", args4[0], " then ", args4[1]]); unwind = 114; - const _91: string = _93; - Guard.note(this.#saved$3, _91); + Guard.note(this.#saved$3, _93); unwind = 137; this.#mark = { n: 1 }; this.#awaitee$4 = new blocksFuture$4(this.#mark); @@ -539,8 +535,7 @@ export class blocksFuture { const args6: rt.Fmt[] = [_136, (f: rt.Formatter) => rt.u32Display(arg4, f)]; const _129: string = rt.fmtFormat(["mark ", args6[0], " ", args6[1]]); unwind = 112; - const _127: string = _129; - Guard.note(this.#guard$2, _127); + Guard.note(this.#guard$2, _129); unwind = 111; _141 = undefined; const _142: Guard.Guard = Guard.new(rt.u32Add(this.#guard$2.id, 800), Log.clone$Clone(this.#guard$2.log)); @@ -825,8 +820,7 @@ export class blocksFuture$4 { poll(_2: rt.Context): rt.Poll { if (this.#state === 0) { const _3: Mark.Mark = { n: 2 }; - const _4: Mark.Mark = this.#mark; - Object.assign(_4, _3); + Object.assign(this.#mark, _3); const _0: rt.Poll = this.#mark.n; this.#state = 1; return _0; diff --git a/ts/src/lower/mir/cfg.rs b/ts/src/lower/mir/cfg.rs index 06e1a8d5b..0aa1f195f 100644 --- a/ts/src/lower/mir/cfg.rs +++ b/ts/src/lower/mir/cfg.rs @@ -451,7 +451,7 @@ pub fn simplify(stmts: &mut Vec) { strip_tail(body, &StmtKind::Break(Some(l.clone()))); } } - StmtKind::While { label, body, .. } => { + StmtKind::While { label, body, .. } | StmtKind::ForOf { label, body, .. } => { simplify(body); if let Some(l) = label { strip_tail(body, &StmtKind::Continue(Some(l.clone()))); @@ -480,12 +480,17 @@ pub fn simplify(stmts: &mut Vec) { StmtKind::Block { label: Some(l), body } | StmtKind::While { label: Some(l), body, .. + } + | StmtKind::ForOf { + label: Some(l), body, .. } => !targets(body, l), _ => false, }; if unused { match &mut stmts[i].kind { - StmtKind::Block { label, .. } | StmtKind::While { label, .. } => *label = None, + StmtKind::Block { label, .. } | StmtKind::While { label, .. } | StmtKind::ForOf { label, .. } => { + *label = None + } _ => unreachable!(), } } @@ -535,7 +540,9 @@ pub fn hoist_else(stmts: &mut Vec) { stmts.splice(i + 1..i + 1, els); } } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } => hoist_else(body), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + hoist_else(body) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| hoist_else(body)); hoist_else(default); @@ -566,7 +573,7 @@ fn adopt_labels(stmts: &mut [Stmt]) { for stmt in stmts.iter_mut() { if let StmtKind::Block { label: Some(b), body } = &mut stmt.kind && let [loop_] = body.as_mut_slice() - && let StmtKind::While { label, body, .. } = &mut loop_.kind + && let StmtKind::While { label, body, .. } | StmtKind::ForOf { label, body, .. } = &mut loop_.kind { let l = label.get_or_insert_with(|| b.clone()).clone(); retarget(body, b, &l); @@ -577,7 +584,9 @@ fn adopt_labels(stmts: &mut [Stmt]) { adopt_labels(then); adopt_labels(els); } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } => adopt_labels(body), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + adopt_labels(body) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| adopt_labels(body)); adopt_labels(default); @@ -600,7 +609,9 @@ fn retarget(stmts: &mut [Stmt], from: &str, to: &str) { retarget(then, from, to); retarget(els, from, to); } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } => retarget(body, from, to), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + retarget(body, from, to) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| retarget(body, from, to)); retarget(default, from, to); @@ -640,7 +651,7 @@ fn rotate(stmts: &mut [Stmt]) { rotate(then); rotate(els); } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } => rotate(body), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => rotate(body), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| rotate(body)); rotate(default); @@ -667,7 +678,9 @@ fn unlabel(stmts: &mut [Stmt], innermost: Option<&str>, in_switch: bool) { } StmtKind::Block { body, .. } => unlabel(body, innermost, in_switch), // An unlabeled loop matches no jump's label. - StmtKind::While { label, body, .. } => unlabel(body, Some(label.as_deref().unwrap_or("")), false), + StmtKind::While { label, body, .. } | StmtKind::ForOf { label, body, .. } => { + unlabel(body, Some(label.as_deref().unwrap_or("")), false) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| unlabel(body, innermost, true)); unlabel(default, innermost, true); @@ -732,7 +745,9 @@ fn targets(stmts: &[Stmt], label: &str) -> bool { stmts.iter().any(|stmt| match &stmt.kind { StmtKind::Break(Some(l)) | StmtKind::Continue(Some(l)) => l == label, StmtKind::If { then, els, .. } => targets(then, label) || targets(els, label), - StmtKind::Block { body, .. } | StmtKind::While { body, .. } => targets(body, label), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + targets(body, label) + } StmtKind::Catch { body, handler, .. } => targets(body, label) || targets(handler, label), StmtKind::Switch { cases, default, .. } => { cases.iter().any(|(_, body)| targets(body, label)) || targets(default, label) diff --git a/ts/src/lower/mir/inline.rs b/ts/src/lower/mir/inline.rs new file mode 100644 index 000000000..0884c0a4f --- /dev/null +++ b/ts/src/lower/mir/inline.rs @@ -0,0 +1,166 @@ +//! Each `const` read once, by the statement right after it, folded into that read: the +//! temporaries lowering leaves where MIR read a local twice, as a bounds check and an +//! index do, or where folding it as it lowered would have reordered reads. + +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; + +use super::{Read, scan, subst, visit_expr, visit_stmt}; +use crate::ts::{Expr, Stmt, StmtKind}; + +/// Fold throughout `stmts`, a function's body, given the names of locals something +/// borrows, which a call can change. +pub(super) fn inline_temps(stmts: &mut Vec, shared: &FxHashSet) { + let mut names: FxHashMap = FxHashMap::default(); + for stmt in stmts.iter() { + visit_stmt(stmt, &mut |e| { + visit_expr(e, &mut |e| { + if let Expr::Ident(name) = e { + *names.entry(name.clone()).or_default() += 1; + } + }) + }); + } + list(stmts, &names, shared); +} + +fn list(stmts: &mut Vec, names: &FxHashMap, shared: &FxHashSet) { + for stmt in stmts.iter_mut() { + match &mut stmt.kind { + StmtKind::If { then, els, .. } => { + list(then, names, shared); + list(els, names, shared); + } + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + list(body, names, shared) + } + StmtKind::Switch { cases, default, .. } => { + cases.iter_mut().for_each(|(_, body)| list(body, names, shared)); + list(default, names, shared); + } + StmtKind::Catch { body, handler, .. } => { + list(body, names, shared); + list(handler, names, shared); + } + _ => {} + } + } + // From the end, so a temporary folds into one that has folded into its reader. + for i in (0..stmts.len().saturating_sub(1)).rev() { + let StmtKind::Decl { + mutable: false, + name, + ty, + init: Some(value), + } = &stmts[i].kind + else { + continue; + }; + // A literal's type comes from its declaration: an array's may be a tuple's. + let typed = ty.is_some() && matches!(super::step::peel(value), Expr::Array(_) | Expr::Object(_)); + if !typed + && names.get(name) == Some(&1) + && let Some(next) = eager(&stmts[i + 1]) + && folds(value, name, next, shared) + { + let StmtKind::Decl { + name, + init: Some(value), + .. + } = stmts.remove(i).kind + else { + unreachable!("matched above") + }; + let next = eager_mut(&mut stmts[i]).expect("found above"); + subst(next, &name, &value); + } + } +} + +/// What evaluating some code may do, as far as moving other code past it goes. +#[derive(Default)] +struct Does { + /// Change something: a call, or an assignment. + writes: bool, + /// Panic without changing anything, as the runtime's arithmetic can. + panics: bool, + /// Read memory a call could change, or a local something borrows. + reads: bool, +} + +impl Does { + fn of(events: &[Read], shared: &FxHashSet) -> Self { + let mut does = Self::default(); + for event in events { + match event { + Read::Effect => does.writes = true, + Read::Panic => does.panics = true, + Read::Memory | Read::Field(_) => does.reads = true, + Read::Ident(name, _) => does.reads |= shared.contains(name.as_str()), + } + } + does + } +} + +/// What `stmt` evaluates first, and always: its expression, an `if`'s condition, a loop's +/// array, or a block's first statement's. +fn eager(stmt: &Stmt) -> Option<&Expr> { + match &stmt.kind { + StmtKind::Expr(e) | StmtKind::Return(Some(e)) | StmtKind::Throw(e) => Some(e), + StmtKind::Decl { init: Some(e), .. } | StmtKind::If { cond: e, .. } | StmtKind::ForOf { iter: e, .. } => { + Some(e) + } + StmtKind::Block { body, .. } => body.first().and_then(eager), + _ => None, + } +} + +fn eager_mut(stmt: &mut Stmt) -> Option<&mut Expr> { + match &mut stmt.kind { + StmtKind::Expr(e) | StmtKind::Return(Some(e)) | StmtKind::Throw(e) => Some(e), + StmtKind::Decl { init: Some(e), .. } | StmtKind::If { cond: e, .. } | StmtKind::ForOf { iter: e, .. } => { + Some(e) + } + StmtKind::Block { body, .. } => body.first_mut().and_then(eager_mut), + _ => None, + } +} + +/// Whether `value`, the temporary `name`'s, can be evaluated where `next` reads it +/// instead of before `next`: the read always runs, and what `next` evaluates first +/// neither changes what `value` sees nor is changed or reordered by it. +fn folds(value: &Expr, name: &str, next: &Expr, shared: &FxHashSet) -> bool { + let mut events = Vec::new(); + scan(next, &mut events, false); + let Some(at) = events.iter().position(|r| matches!(r, Read::Ident(n, _) if n == name)) else { + return false; + }; + if matches!(&events[at], Read::Ident(_, true)) { + return false; + } + let before = Does::of(&events[..at], shared); + let mut own = Vec::new(); + scan(value, &mut own, false); + let it = Does::of(&own, shared); + // A local one reads that the other assigns. + let crossed = |events: &[Read], assigns: &dyn Fn(&str) -> bool| { + events.iter().any(|r| matches!(r, Read::Ident(n, _) if assigns(n))) + }; + let assigned = (before.writes && crossed(&own, &|n| expr_assigns(next, n))) + || (it.writes && crossed(&events[..at], &|n| expr_assigns(value, n))); + !assigned + && !(before.writes && (it.writes || it.panics || it.reads)) + && !(it.writes && (before.writes || before.panics || before.reads)) + && !(before.panics && it.panics) +} + +/// Whether `e` assigns the variable `name` whole. +fn expr_assigns(e: &Expr, name: &str) -> bool { + let mut found = false; + visit_expr(e, &mut |e| { + if let Expr::Assign(target, _) | Expr::Postfix(target, _) = e { + found |= matches!(&**target, Expr::Ident(n) if n == name); + } + }); + found +} diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 80606b4fe..ed20f593b 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -14,6 +14,7 @@ mod call; mod cfg; pub mod coroutine; pub mod glue; +mod inline; mod place; mod rvalue; mod step; @@ -1234,6 +1235,11 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { cfg::hoist_else(&mut out); declare_in_place(&mut out); cfg::tidy_loops(&mut out); + // A loop's own labels first, which its header's `break` names. + step::for_of(&mut out); + inline::inline_temps(&mut out, &self.shared); + // A loop can start by leaving now that what it tests is folded in. + cfg::tidy_loops(&mut out); out } @@ -1485,7 +1491,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { }, Read::Memory => seen_memory = true, Read::Field(name) => seen_memory |= !self.frozen_names.contains(name.as_str()), - Read::Effect => seen_effect = true, + Read::Effect | Read::Panic => seen_effect = true, } } // What stays pending past this statement, and what must run before it. @@ -1671,12 +1677,12 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { for value in parts { let mut events = Vec::new(); scan(&value, &mut events, false); - let effect = events.iter().any(|r| matches!(r, Read::Effect)); + let effect = events.iter().any(|r| matches!(r, Read::Effect | Read::Panic)); let memory = events.iter().any(|r| match r { Read::Memory => true, Read::Field(name) => !self.frozen_names.contains(name.as_str()), Read::Ident(name, _) => self.shared.contains(name.as_str()), - Read::Effect => false, + Read::Effect | Read::Panic => false, }); if !effect && !memory { names.push(value); @@ -2377,6 +2383,8 @@ enum Read { Field(String), /// A call, which may do anything. Effect, + /// A call of the runtime's that reads its arguments only, and may panic. + Panic, } fn scan_stmt(stmt: &Stmt, reads: &mut Vec, lazy: bool) { @@ -2391,6 +2399,10 @@ fn scan_stmt(stmt: &Stmt, reads: &mut Vec, lazy: bool) { scan(cond, reads, true); body.iter().for_each(|s| scan_stmt(s, reads, true)); } + StmtKind::ForOf { iter, body, .. } => { + scan(iter, reads, lazy); + body.iter().for_each(|s| scan_stmt(s, reads, true)); + } StmtKind::Block { body, .. } => body.iter().for_each(|s| scan_stmt(s, reads, lazy)), _ => {} } @@ -2428,7 +2440,10 @@ fn scan(e: &Expr, reads: &mut Vec, lazy: bool) { f => scan(f, reads, lazy), } args.iter().for_each(|e| scan(e, reads, lazy)); - reads.push(Read::Effect); + reads.push(match &**f { + Expr::Rt(name) if reads_only(name) => Read::Panic, + _ => Read::Effect, + }); } Expr::Unary(_, e) | Expr::Located(_, e) | Expr::As(e, _) => scan(e, reads, lazy), Expr::Postfix(e, _) => { @@ -2465,6 +2480,46 @@ fn scan(e: &Expr, reads: &mut Vec, lazy: bool) { } } +/// Whether the runtime's function `name` only reads its arguments, if it may panic: a +/// bounds check, or integer arithmetic or a comparison. +fn reads_only(name: &str) -> bool { + if matches!(name, "idx" | "at" | "min" | "max" | "lt") { + return true; + } + let Some(op) = [ + "usize", "isize", "u128", "i128", "u16", "i16", "u32", "i32", "u64", "i64", "u8", "i8", + ] + .iter() + .find_map(|ty| name.strip_prefix(ty)) else { + return false; + }; + matches!( + op, + "Add" + | "Sub" + | "Mul" + | "Div" + | "Rem" + | "Neg" + | "Shl" + | "Shr" + | "And" + | "Or" + | "Xor" + | "Not" + | "Eq" + | "Ne" + | "Lt" + | "Le" + | "Gt" + | "Ge" + | "Max" + | "Min" + | "Cast" + | "Low" + ) +} + /// Replace the one read of `name` in `stmt` with `value`; whether it was there. fn subst_stmt(stmt: &mut Stmt, name: &str, value: &Expr) -> bool { match &mut stmt.kind { @@ -2527,8 +2582,8 @@ fn scan_reads(stmt: &Stmt, out: &mut Vec) { visit(cond); then.iter().chain(els).for_each(|s| scan_reads(s, out)); } - StmtKind::While { cond, body, .. } => { - reads_of(cond, out); + StmtKind::While { cond: e, body, .. } | StmtKind::ForOf { iter: e, body, .. } => { + reads_of(e, out); body.iter().for_each(|s| scan_reads(s, out)); } StmtKind::Block { body, .. } => body.iter().for_each(|s| scan_reads(s, out)), @@ -2601,7 +2656,9 @@ fn strip_assignments(stmts: &mut Vec, unread: &FxHashSet) { strip_assignments(then, unread); strip_assignments(els, unread); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => strip_assignments(body, unread), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + strip_assignments(body, unread) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| strip_assignments(body, unread)); strip_assignments(default, unread); @@ -2667,7 +2724,7 @@ fn place_declaration(stmts: &mut [Stmt], name: &str, ty: &Type, total: usize, mu |body: &mut Vec| list_names(body, name) == total && place_declaration(body, name, ty, total, mutable); match &mut stmts[i].kind { StmtKind::If { then, els, .. } => place(then) || place(els), - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => place(body), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => place(body), StmtKind::Catch { body, handler, .. } => place(body) || place(handler), StmtKind::Switch { cases, default, .. } => cases.iter_mut().any(|(_, body)| place(body)) || place(default), _ => false, @@ -2714,8 +2771,8 @@ fn visit_stmt(stmt: &Stmt, f: &mut dyn FnMut(&Expr)) { f(cond); then.iter().chain(els).for_each(|s| visit_stmt(s, f)); } - StmtKind::While { cond, body, .. } => { - f(cond); + StmtKind::While { cond: e, body, .. } | StmtKind::ForOf { iter: e, body, .. } => { + f(e); body.iter().for_each(|s| visit_stmt(s, f)); } StmtKind::Block { body, .. } => body.iter().for_each(|s| visit_stmt(s, f)), @@ -2900,7 +2957,9 @@ fn drop_self_assignments(stmts: &mut Vec) { drop_self_assignments(then); drop_self_assignments(els); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => drop_self_assignments(body), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + drop_self_assignments(body) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| drop_self_assignments(body)); drop_self_assignments(default); @@ -2923,7 +2982,9 @@ fn return_in_place(stmts: &mut Vec, caught: &FxHashSet) { return_in_place(then, caught); return_in_place(els, caught); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => return_in_place(body, caught), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + return_in_place(body, caught) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| return_in_place(body, caught)); return_in_place(default, caught); @@ -3000,7 +3061,9 @@ fn handler_reads(stmts: &[Stmt], out: &mut Vec) { handler_reads(then, out); handler_reads(els, out); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => handler_reads(body, out), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + handler_reads(body, out) + } StmtKind::Switch { cases, default, .. } => { cases.iter().for_each(|(_, body)| handler_reads(body, out)); handler_reads(default, out); @@ -3064,7 +3127,9 @@ fn breaks_to_return(stmts: &mut [Stmt], label: &str, ret: &Stmt) { breaks_to_return(then, label, ret); breaks_to_return(els, label, ret); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => breaks_to_return(body, label, ret), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + breaks_to_return(body, label, ret) + } StmtKind::Switch { cases, default, .. } => { cases .iter_mut() diff --git a/ts/src/lower/mir/step.rs b/ts/src/lower/mir/step.rs index 82adb926c..3b6ef3eeb 100644 --- a/ts/src/lower/mir/step.rs +++ b/ts/src/lower/mir/step.rs @@ -331,3 +331,194 @@ pub(super) fn stepped_field(it: &Expr, key: &str) -> Expr { it => it.clone().member(key), } } + +/// Each loop over an array iterator stepped in place that only the loop steps, as +/// `for (const item of array)`: a `while (true)` whose first statements take the next +/// item and leave on `rt.DONE`. Nothing else names the index, so nothing sees where it +/// stopped. +pub(super) fn for_of(stmts: &mut Vec) { + let mut names: FxHashMap = FxHashMap::default(); + for stmt in stmts.iter() { + super::visit_stmt(stmt, &mut |e| { + super::visit_expr(e, &mut |e| { + if let Expr::Ident(name) = e { + *names.entry(name.clone()).or_default() += 1; + } + }) + }); + } + // The variables declared `= 0`, as an index starts. + let mut zeros = FxHashSet::default(); + decls(stmts, &mut |name, init| { + if matches!(init, Expr::Lit(l) if l == "0") { + zeros.insert(name.to_string()); + } + }); + let mut indexes = FxHashSet::default(); + loops(stmts, &names, &zeros, &mut indexes); + if !indexes.is_empty() { + drop_decls(stmts, &indexes); + } +} + +/// Call `f` on the name and value of each declaration in `stmts` that has one. +fn decls(stmts: &[Stmt], f: &mut dyn FnMut(&str, &Expr)) { + for stmt in stmts { + match &stmt.kind { + StmtKind::Decl { + name, init: Some(init), .. + } => f(name, init), + StmtKind::If { then, els, .. } => { + decls(then, f); + decls(els, f); + } + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + decls(body, f) + } + StmtKind::Switch { cases, default, .. } => { + cases.iter().for_each(|(_, body)| decls(body, f)); + decls(default, f); + } + StmtKind::Catch { body, handler, .. } => { + decls(body, f); + decls(handler, f); + } + _ => {} + } + } +} + +/// Rewrite the loops in `stmts`, collecting the indexes they no longer read. +fn loops( + stmts: &mut [Stmt], + names: &FxHashMap, + zeros: &FxHashSet, + indexes: &mut FxHashSet, +) { + for stmt in stmts.iter_mut() { + // The array and the index are declared, and named only by this loop's header. + if let StmtKind::While { label, cond, body } = &mut stmt.kind + && matches!(cond, Expr::Lit(l) if l == "true") + && let Some((item, array, index)) = header(body, label.as_deref()) + && names.get(&array) == Some(&2) + && names.get(&index) == Some(&2) + && zeros.contains(&index) + { + let mut body: Vec = std::mem::take(body).into_iter().skip(2).collect(); + let mut name = item; + // `const entry = item;` names the item, when nothing else reads it. + if let Some(StmtKind::Decl { + mutable: false, + name: to, + init: Some(Expr::Ident(from)), + .. + }) = body.first().map(|s| &s.kind) + && *from == name + && super::list_names(&body, &name) == 1 + { + name = to.clone(); + body.remove(0); + } + indexes.insert(index); + stmt.kind = StmtKind::ForOf { + label: label.take(), + name, + iter: Expr::ident(array), + body, + }; + } + match &mut stmt.kind { + StmtKind::If { then, els, .. } => { + loops(then, names, zeros, indexes); + loops(els, names, zeros, indexes); + } + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + loops(body, names, zeros, indexes) + } + StmtKind::Switch { cases, default, .. } => { + cases + .iter_mut() + .for_each(|(_, body)| loops(body, names, zeros, indexes)); + loops(default, names, zeros, indexes); + } + StmtKind::Catch { body, handler, .. } => { + loops(body, names, zeros, indexes); + loops(handler, names, zeros, indexes); + } + _ => {} + } + } +} + +/// The item, array, and index of a loop that starts `const item = i < s.length ? +/// s[i++] : rt.DONE; if (item === rt.DONE) break;`, the `break` leaving it. +fn header(body: &[Stmt], label: Option<&str>) -> Option<(String, String, String)> { + let [next, test, ..] = body else { + return None; + }; + let StmtKind::Decl { + mutable: false, + name: item, + init: Some(init), + .. + } = &next.kind + else { + return None; + }; + let Expr::Cond(c, a, b) = peel(init) else { + return None; + }; + let (Expr::Binary(i, "<", len), Expr::Index(s, at), Expr::Rt(done)) = (peel(c), peel(a), peel(b)) else { + return None; + }; + let (Expr::Ident(index), Expr::Member(s2, Key::Name(length)), Expr::Ident(array), Expr::Postfix(i2, "++")) = + (peel(i), peel(len), peel(s), peel(at)) + else { + return None; + }; + let same = |e: &Expr, name: &str| matches!(peel(e), Expr::Ident(n) if n == name); + if done != "DONE" || length != "length" || !same(s2, array) || !same(i2, index) { + return None; + } + let StmtKind::If { cond, then, els } = &test.kind else { + return None; + }; + let leaves = matches!(then.as_slice(), [Stmt { kind: StmtKind::Break(target), .. }] + if target.is_none() || target.as_deref() == label); + let tests = matches!(peel(cond), Expr::Binary(l, "===", r) + if same(l, item) && matches!(peel(r), Expr::Rt(d) if d == "DONE")); + (leaves && tests && els.is_empty()).then(|| (item.clone(), array.clone(), index.clone())) +} + +/// `e` without its source location. +pub(super) fn peel(e: &Expr) -> &Expr { + match e { + Expr::Located(_, e) => peel(e), + e => e, + } +} + +/// Drop the declarations of `names`, which nothing reads any more. +fn drop_decls(stmts: &mut Vec, names: &FxHashSet) { + stmts.retain(|s| !matches!(&s.kind, StmtKind::Decl { name, .. } if names.contains(name))); + for stmt in stmts.iter_mut() { + match &mut stmt.kind { + StmtKind::If { then, els, .. } => { + drop_decls(then, names); + drop_decls(els, names); + } + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + drop_decls(body, names) + } + StmtKind::Switch { cases, default, .. } => { + cases.iter_mut().for_each(|(_, body)| drop_decls(body, names)); + drop_decls(default, names); + } + StmtKind::Catch { body, handler, .. } => { + drop_decls(body, names); + drop_decls(handler, names); + } + _ => {} + } + } +} diff --git a/ts/src/print.rs b/ts/src/print.rs index 1d05f2eac..cda3e9204 100644 --- a/ts/src/print.rs +++ b/ts/src/print.rs @@ -313,8 +313,8 @@ impl Refs { self.stmts(program, then); self.stmts(program, els); } - StmtKind::While { cond, body, .. } => { - self.expr(program, cond); + StmtKind::While { cond: e, body, .. } | StmtKind::ForOf { iter: e, body, .. } => { + self.expr(program, e); self.stmts(program, body); } StmtKind::Block { body, .. } => self.stmts(program, body), @@ -746,6 +746,21 @@ impl Printer<'_> { self.start(); self.write("}\n"); } + StmtKind::ForOf { + label, + name, + iter, + body, + } => { + self.label(label); + let name = self.local(name).to_string(); + self.write(&format!("for (const {name} of ")); + self.expr(iter, 2); + self.write(") {\n"); + self.block_body(body); + self.start(); + self.write("}\n"); + } StmtKind::Block { label, body } => { self.label(label); self.write("{\n"); @@ -1155,6 +1170,11 @@ fn collect_locals(stmts: &[Stmt], out: &mut Vec) { collect_expr_locals(cond, out); collect_locals(body, out); } + StmtKind::ForOf { name, iter, body, .. } => { + out.push(name.clone()); + collect_expr_locals(iter, out); + collect_locals(body, out); + } StmtKind::Block { body, .. } => collect_locals(body, out), StmtKind::Catch { body, name, handler } => { collect_locals(body, out); diff --git a/ts/src/ts.rs b/ts/src/ts.rs index d88ba77a1..f95469f25 100644 --- a/ts/src/ts.rs +++ b/ts/src/ts.rs @@ -200,6 +200,13 @@ pub enum StmtKind { cond: Expr, body: Vec, }, + /// `for (const name of iter) body`, over an array. + ForOf { + label: Option, + name: String, + iter: Expr, + body: Vec, + }, Block { label: Option, body: Vec, @@ -280,7 +287,7 @@ fn breaks_out(stmts: &[Stmt], label: Option<&str>, nested: bool) -> bool { StmtKind::Switch { cases, default, .. } => { cases.iter().any(|(_, body)| breaks_out(body, label, true)) || breaks_out(default, label, true) } - StmtKind::While { body, .. } => breaks_out(body, label, true), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => breaks_out(body, label, true), _ => false, }) } From 109279c31893b30bcc94789417e0be6da6ef84cd Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:19:56 -0700 Subject: [PATCH 03/15] feat(ts): share a coroutine field among locals never live at once Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/model.ts | 229 ++++++++++++++--------------- ts/src/lower/mir/coroutine.rs | 20 ++- 2 files changed, 127 insertions(+), 122 deletions(-) diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 35e740b2c..204016db7 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -200,25 +200,20 @@ export class blocksFuture { #saved!: Guard.Guard; #awaitee!: rt.Future; #slots!: Guard.Guard[]; - #saved$2!: Guard.Guard; #awaitee$2!: rt.Future; #tally!: Tally.Tally; - #saved$3!: Guard.Guard; - #saved$4!: rt.u32; + #saved$2!: rt.u32; #awaitee$3!: rt.Future; #mark!: Mark.Mark; - #replaced!: rt.u32; - #awaitee$4!: rt.Future; #nested!: Inner.Inner; - #chosen!: Guard.Guard; - #awaitee$5!: rt.Future; + #awaitee$4!: rt.Future; + #saved$3!: boolean; + #saved$4!: boolean; #saved$5!: boolean; #saved$6!: boolean; #saved$7!: boolean; #saved$8!: boolean; #saved$9!: boolean; - #saved$10!: boolean; - #saved$11!: boolean; constructor(rx: Consumer.Consumer, guard: Guard.Guard, moves: boolean) { this.#rx = rx; @@ -243,15 +238,15 @@ export class blocksFuture { rt.drop(this.#awaitee); unwind = 57; rt.drop(this.#saved); - this.#saved$11 = false; + this.#saved$9 = false; break b0; } if (this.#state === 4) { unwind = 51; rt.drop(this.#awaitee$2); unwind = 52; - rt.drop(this.#saved$2); - this.#saved$10 = false; + rt.drop(this.#saved); + this.#saved$8 = false; break b1; } if (this.#state === 5) { @@ -259,42 +254,42 @@ export class blocksFuture { rt.drop(this.#awaitee$3); } else if (this.#state === 6) { unwind = 44; - rt.drop(this.#awaitee$4); + rt.drop(this.#awaitee$3); } else if (this.#state === 7) { unwind = 37; - rt.drop(this.#awaitee$5); + rt.drop(this.#awaitee$4); unwind = 40; - rt.drop(this.#chosen); + rt.drop(this.#saved); unwind = 42; rt.drop(this.#nested); } else { return; } - this.#saved$9 = false; + this.#saved$7 = false; } unwind = 55; rt.dropAll(this.#slots); } - if (this.#saved$6) { + if (this.#saved$4) { unwind = 60; rt.drop(this.#second); } - this.#saved$6 = false; - if (this.#saved$7) { + this.#saved$4 = false; + if (this.#saved$5) { unwind = 61; rt.drop(this.#first); } - this.#saved$7 = false; - if (this.#saved$5) { + this.#saved$5 = false; + if (this.#saved$3) { unwind = 62; rt.drop(this.#guard$2); } - this.#saved$5 = false; - if (this.#saved$8) { + this.#saved$3 = false; + if (this.#saved$6) { unwind = 0; rt.drop(this.#rx$2); } - this.#saved$8 = false; + this.#saved$6 = false; } catch (e) { b8: { b9: { @@ -312,7 +307,7 @@ export class blocksFuture { throw e; } if (unwind === 37) { - rt.drop(this.#chosen); + rt.drop(this.#saved); break b18; } if (unwind === 40) { @@ -328,7 +323,7 @@ export class blocksFuture { break b15; } if (unwind === 51) { - rt.drop(this.#saved$2); + rt.drop(this.#saved); break b19; } if (unwind === 52) { @@ -352,40 +347,40 @@ export class blocksFuture { rt.drop(this.#guard); break b8; } - this.#saved$11 = false; + this.#saved$9 = false; break b12; } - this.#saved$10 = false; + this.#saved$8 = false; break b14; } rt.drop(this.#nested); } } } - this.#saved$9 = false; + this.#saved$7 = false; } rt.dropAll(this.#slots); } } - if (this.#saved$6) { + if (this.#saved$4) { rt.drop(this.#second); } } - this.#saved$6 = false; - if (this.#saved$7) { + this.#saved$4 = false; + if (this.#saved$5) { rt.drop(this.#first); } } - this.#saved$7 = false; - if (this.#saved$5) { + this.#saved$5 = false; + if (this.#saved$3) { rt.drop(this.#guard$2); } } - this.#saved$5 = false; - if (this.#saved$8) { + this.#saved$3 = false; + if (this.#saved$6) { rt.drop(this.#rx$2); } - this.#saved$8 = false; + this.#saved$6 = false; } throw e; } @@ -404,31 +399,31 @@ export class blocksFuture { b3: { if (this.#state === 0) { unwind = 132; - this.#saved$8 = false; - this.#saved$5 = false; - this.#saved$7 = false; this.#saved$6 = false; - this.#saved$11 = false; - this.#saved$10 = false; + this.#saved$3 = false; + this.#saved$5 = false; + this.#saved$4 = false; this.#saved$9 = false; - this.#saved$8 = true; + this.#saved$8 = false; + this.#saved$7 = false; + this.#saved$6 = true; this.#rx$2 = this.#rx; - this.#saved$5 = true; + this.#saved$3 = true; this.#guard$2 = this.#guard; this.#moves$2 = this.#moves; this.#first = Guard.new(rt.u32Add(this.#guard$2.id, 200), Log.clone$Clone(this.#guard$2.log)); unwind = 131; - this.#saved$7 = true; + this.#saved$5 = true; this.#second = Guard.new(rt.u32Add(this.#guard$2.id, 300), Log.clone$Clone(this.#guard$2.log)); unwind = 142; - this.#saved$6 = true; + this.#saved$4 = true; rt.drop(new blocksFuture$2(this.#first)); turns(this.#guard$2.log, rt.u32Rem(this.#guard$2.id, 5)); temporaries(this.#guard$2.log, this.#guard$2.id); unwind = 130; this.#saved = Guard.new(rt.u32Add(this.#guard$2.id, 900), Log.clone$Clone(this.#guard$2.log)); unwind = 128; - this.#saved$11 = true; + this.#saved$9 = true; this.#awaitee = new recvFuture(this.#rx$2); } else if (this.#state === 1) { rt.asyncFnResumed(); @@ -452,18 +447,18 @@ export class blocksFuture { unwind = 126; const result: rt.u64 | undefined = _32; rt.drop(this.#awaitee); - this.#saved$11 = false; + this.#saved$9 = false; this.#waited = consume(this.#saved, result); unwind = 142; - this.#saved$11 = false; + this.#saved$9 = false; _40 = Guard.new(rt.u32Add(this.#guard$2.id, 910), Log.clone$Clone(this.#guard$2.log)); unwind = 124; const _46: Guard.Guard = Guard.new(rt.u32Add(this.#guard$2.id, 920), Log.clone$Clone(this.#guard$2.log)); unwind = 122; this.#slots = [_40, _46]; - this.#saved$2 = Guard.new(rt.u32Add(this.#guard$2.id, 930), Log.clone$Clone(this.#guard$2.log)); + this.#saved = Guard.new(rt.u32Add(this.#guard$2.id, 930), Log.clone$Clone(this.#guard$2.log)); unwind = 120; - this.#saved$10 = true; + this.#saved$8 = true; this.#awaitee$2 = new slotFuture(this.#rx$2, this.#slots.length); } else { this.#state = 3; @@ -482,9 +477,9 @@ export class blocksFuture { unwind = 44; rt.drop(this.#slots[result2]); unwind = 123; - this.#saved$10 = false; - this.#slots[result2] = this.#saved$2; - this.#saved$10 = false; + this.#saved$8 = false; + this.#slots[result2] = this.#saved; + this.#saved$8 = false; const arg = ([this.#waited] as [rt.u64])[0]; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(arg, f)]; const _78: string = rt.fmtFormat(["slot after ", args2[0]]); @@ -492,12 +487,12 @@ export class blocksFuture { Guard.note(this.#slots[0], _78); unwind = 137; this.#tally = { n: this.#guard$2.id }; - this.#saved$9 = true; + this.#saved$7 = true; seen = new blocksFuture$3(copy$Tally(this.#tally)); this.#tally.n = rt.u32Add(this.#tally.n, 1000); - this.#saved$3 = this.#guard$2; - this.#saved$4 = this.#tally.n; - this.#saved$9 = false; + this.#saved = this.#guard$2; + this.#saved$2 = this.#tally.n; + this.#saved$7 = false; this.#awaitee$3 = seen; } else { this.#state = 4; @@ -510,26 +505,26 @@ export class blocksFuture { unwind = 137; const _98: rt.u32 = _101; rt.drop(this.#awaitee$3); - const arg2 = this.#saved$4; + const arg2 = this.#saved$2; const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f), (f: rt.Formatter) => rt.u32Display(_98, f)]; const _93: string = rt.fmtFormat(["tally ", args4[0], " then ", args4[1]]); unwind = 114; - Guard.note(this.#saved$3, _93); + Guard.note(this.#saved, _93); unwind = 137; this.#mark = { n: 1 }; - this.#awaitee$4 = new blocksFuture$4(this.#mark); + this.#awaitee$3 = new blocksFuture$4(this.#mark); } else { this.#state = 5; return rt.Pending; } } unwind = 113; - const _117: rt.Poll = this.#awaitee$4.poll(_2); + const _117: rt.Poll = this.#awaitee$3.poll(_2); if (_117 !== rt.Pending) { unwind = 137; - this.#replaced = _117; - rt.drop(this.#awaitee$4); - const arg3 = this.#replaced; + this.#saved$2 = _117; + rt.drop(this.#awaitee$3); + const arg3 = this.#saved$2; const _136: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg3, f); const arg4 = this.#mark.n; const args6: rt.Fmt[] = [_136, (f: rt.Formatter) => rt.u32Display(arg4, f)]; @@ -545,46 +540,46 @@ export class blocksFuture { this.#nested = new Inner.Inner({ outer: _149 }); const third: Guard.Guard = Guard.new(rt.u32Add(this.#guard$2.id, 400), Log.clone$Clone(this.#guard$2.log)); if (!this.#moves$2) { - this.#chosen = third; + this.#saved = third; } else { - this.#chosen = third; + this.#saved = third; } unwind = 109; - Guard.note(this.#chosen, "chosen"); + Guard.note(this.#saved, "chosen"); if (this.#moves$2) { - this.#saved$5 = false; + this.#saved$3 = false; rt.drop(new blocksFuture$5(this.#guard$2)); } - this.#saved$7 = false; + this.#saved$5 = false; + this.#saved$4 = false; this.#saved$6 = false; - this.#saved$8 = false; - this.#awaitee$5 = new blocksFuture$6(this.#first, this.#second, this.#rx$2); + this.#awaitee$4 = new blocksFuture$6(this.#first, this.#second, this.#rx$2); } else { this.#state = 6; return rt.Pending; } } unwind = 108; - const _164: rt.Poll = this.#awaitee$5.poll(_2); + const _164: rt.Poll = this.#awaitee$4.poll(_2); if (_164 !== rt.Pending) { unwind = 109; const result5: rt.u64 = _164; - rt.drop(this.#awaitee$5); + rt.drop(this.#awaitee$4); unwind = 110; - rt.drop(this.#chosen); + rt.drop(this.#saved); unwind = 137; rt.drop(this.#nested); unwind = 142; - this.#saved$9 = false; - rt.dropAll(this.#slots); - this.#saved$6 = false; this.#saved$7 = false; - if (this.#saved$5) { + rt.dropAll(this.#slots); + this.#saved$4 = false; + this.#saved$5 = false; + if (this.#saved$3) { unwind = 133; rt.drop(this.#guard$2); } - this.#saved$5 = false; - this.#saved$8 = false; + this.#saved$3 = false; + this.#saved$6 = false; this.#state = 1; return result5; } @@ -604,12 +599,12 @@ export class blocksFuture { throw e; } if (unwind === 44) { - this.#saved$10 = false; - this.#slots[result2] = this.#saved$2; + this.#saved$8 = false; + this.#slots[result2] = this.#saved; break b13; } if (unwind === 108) { - rt.drop(this.#awaitee$5); + rt.drop(this.#awaitee$4); break b16; } if (unwind === 109) { @@ -626,7 +621,7 @@ export class blocksFuture { break b14; } if (unwind === 113) { - rt.drop(this.#awaitee$4); + rt.drop(this.#awaitee$3); break b14; } if (unwind === 114) { @@ -644,12 +639,12 @@ export class blocksFuture { break b13; } if (unwind === 120) { - rt.drop(this.#saved$2); - this.#saved$10 = false; + rt.drop(this.#saved); + this.#saved$8 = false; break b12; } if (unwind === 122) { - this.#saved$10 = false; + this.#saved$8 = false; break b12; } if (unwind === 123) { @@ -664,11 +659,11 @@ export class blocksFuture { } else if (unwind !== 126) { if (unwind === 128) { rt.drop(this.#saved); - this.#saved$11 = false; + this.#saved$9 = false; break b11; } if (unwind === 130) { - this.#saved$11 = false; + this.#saved$9 = false; break b11; } if (unwind === 131) { @@ -688,48 +683,48 @@ export class blocksFuture { } break b11; } - if (this.#saved$11) { + if (this.#saved$9) { rt.drop(this.#saved); } - this.#saved$11 = false; + this.#saved$9 = false; break b11; } - rt.drop(this.#chosen); + rt.drop(this.#saved); } rt.drop(this.#nested); } - if (this.#saved$9) { + if (this.#saved$7) { rt.drop(seen); } - this.#saved$9 = false; + this.#saved$7 = false; break b12; } - if (this.#saved$10) { - rt.drop(this.#saved$2); + if (this.#saved$8) { + rt.drop(this.#saved); } - this.#saved$10 = false; + this.#saved$8 = false; } rt.dropAll(this.#slots); } - if (this.#saved$6) { + if (this.#saved$4) { rt.drop(this.#second); } } - this.#saved$6 = false; - if (this.#saved$7) { + this.#saved$4 = false; + if (this.#saved$5) { rt.drop(this.#first); } } - this.#saved$7 = false; - if (this.#saved$5) { + this.#saved$5 = false; + if (this.#saved$3) { rt.drop(this.#guard$2); } } - this.#saved$5 = false; - if (this.#saved$8) { + this.#saved$3 = false; + if (this.#saved$6) { rt.drop(this.#rx$2); } - this.#saved$8 = false; + this.#saved$6 = false; this.#state = 2; throw e; } @@ -1508,8 +1503,6 @@ export class drainFuture { #depth$2!: rt.u32; #total!: rt.u64; #awaitee!: rt.Future; - #awaitee$2!: rt.Future; - #awaitee$3!: rt.Future; constructor(rx: Consumer.Consumer, depth: rt.u32) { this.#rx = rx; @@ -1528,10 +1521,10 @@ export class drainFuture { rt.drop(this.#awaitee); } else if (this.#state === 4) { unwind = 17; - rt.drop(this.#awaitee$2); + rt.drop(this.#awaitee); } else if (this.#state === 5) { unwind = 15; - rt.drop(this.#awaitee$3); + rt.drop(this.#awaitee); } else { return; } @@ -1586,21 +1579,21 @@ export class drainFuture { } if (this.#depth$2 === 4) { unwind = 36; - this.#awaitee$2 = new level3Future(this.#rx$2); + this.#awaitee = new level3Future(this.#rx$2); bb0 = 15; continue; } unwind = 36; - this.#awaitee$3 = new level15Future(this.#rx$2); + this.#awaitee = new level15Future(this.#rx$2); bb0 = 22; continue; case 22: unwind = 33; - const _29: rt.Poll = this.#awaitee$3.poll(_2); + const _29: rt.Poll = this.#awaitee.poll(_2); if (_29 !== rt.Pending) { unwind = 36; next = _29; - rt.drop(this.#awaitee$3); + rt.drop(this.#awaitee); bb0 = 27; continue; } @@ -1608,11 +1601,11 @@ export class drainFuture { return rt.Pending; case 15: unwind = 34; - const _18: rt.Poll = this.#awaitee$2.poll(_2); + const _18: rt.Poll = this.#awaitee.poll(_2); if (_18 !== rt.Pending) { unwind = 36; next = _18; - rt.drop(this.#awaitee$2); + rt.drop(this.#awaitee); bb0 = 27; continue; } @@ -1649,9 +1642,9 @@ export class drainFuture { throw e; } if (unwind === 33) { - rt.drop(this.#awaitee$3); + rt.drop(this.#awaitee); } else if (unwind === 34) { - rt.drop(this.#awaitee$2); + rt.drop(this.#awaitee); } else if (unwind === 35) { rt.drop(this.#awaitee); } else if (unwind !== 36) { diff --git a/ts/src/lower/mir/coroutine.rs b/ts/src/lower/mir/coroutine.rs index 8e2970389..a1474099a 100644 --- a/ts/src/lower/mir/coroutine.rs +++ b/ts/src/lower/mir/coroutine.rs @@ -107,7 +107,21 @@ pub fn info<'tcx>(t: &mut Translator<'_, 'tcx>, def_id: DefId, args: GenericArgs } }; let mut saved = IndexVec::new(); - for field in layout.field_tys.iter() { + // Locals of one type that are never live at once share a field, as rustc overlaps + // them in memory: each `.await` of a future of one type keeps it in the same one. + let mut shared: Vec<(FieldId, Type, Vec)> = Vec::new(); + for (local, field) in layout.field_tys.iter_enumerated() { + let ty = t.subst(args, field.ty); + // A local held across an `.await`, refused as any variable is. + let ty = t.held_ty(ty, field.source_info.span); + let free = shared + .iter_mut() + .find(|(_, of, locals)| *of == ty && locals.iter().all(|&l| !layout.storage_conflicts.contains(l, local))); + if let Some((id, _, locals)) = free { + locals.push(local); + saved.push(*id); + continue; + } // rustc's own locals, such as `__awaitee`, start with `_`. let name = match field .debuginfo_name @@ -118,9 +132,7 @@ pub fn info<'tcx>(t: &mut Translator<'_, 'tcx>, def_id: DefId, args: GenericArgs }; let id = t.program.field(sym, name); saved.push(id); - let ty = t.subst(args, field.ty); - // A local held across an `.await`, refused as any variable is. - let ty = t.held_ty(ty, field.source_info.span); + shared.push((id, ty.clone(), vec![local])); fields.push(ts::Field { id, ty, From f2362c13e787a87720c5f8e4b242c7f8388b8ae6 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:25:58 -0700 Subject: [PATCH 04/15] feat(ts): keep a coroutine's argument in its own field Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/model.ts | 115 ++++++++++++----------------- ts/src/lower/mir/coroutine.rs | 90 +++++++++++++++++++++- ts/src/lower/mir/mod.rs | 24 +++++- 3 files changed, 158 insertions(+), 71 deletions(-) diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 204016db7..db955650d 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -24,8 +24,6 @@ export class sumFuture { #state: number = 0; #rx: Consumer.Consumer; #guard: Guard.Guard; - #rx$2!: Consumer.Consumer; - #guard$2!: Guard.Guard; #inner!: Guard.Guard; #total!: rt.u64; #awaitee!: rt.Future; @@ -49,9 +47,9 @@ export class sumFuture { unwind = 12; rt.drop(this.#inner); unwind = 13; - rt.drop(this.#guard$2); + rt.drop(this.#guard); unwind = 0; - rt.drop(this.#rx$2); + rt.drop(this.#rx); } } catch (e) { b0: { @@ -68,9 +66,9 @@ export class sumFuture { rt.drop(this.#guard); break b0; } - rt.drop(this.#guard$2); + rt.drop(this.#guard); } - rt.drop(this.#rx$2); + rt.drop(this.#rx); } throw e; } @@ -85,9 +83,7 @@ export class sumFuture { case 0: if (this.#state === 0) { unwind = 33; - this.#rx$2 = this.#rx; - this.#guard$2 = this.#guard; - this.#inner = Guard.new(rt.u32Add(this.#guard$2.id, 100), Log.clone$Clone(this.#guard$2.log)); + this.#inner = Guard.new(rt.u32Add(this.#guard.id, 100), Log.clone$Clone(this.#guard.log)); this.#total = 0; bb0 = 4; continue; @@ -102,7 +98,7 @@ export class sumFuture { } case 4: unwind = 32; - this.#awaitee = new recvFuture(this.#rx$2); + this.#awaitee = new recvFuture(this.#rx); bb0 = 7; continue; case 7: @@ -115,11 +111,11 @@ export class sumFuture { if (result !== undefined) { const value: rt.u64 = result; if (!(value !== 99)) { - const arg2 = ([this.#guard$2.id] as [rt.u32])[0]; + const arg2 = ([this.#guard.id] as [rt.u32])[0]; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f)]; rt.panicFmt(["g", args2[0], " poisoned"]); } else { - const arg = this.#guard$2.id; + const arg = this.#guard.id; const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg, f), (f: rt.Formatter) => rt.u64Display(value, f)]; const _32: string = rt.fmtFormat(["g", args4[0], " got ", args4[1]]); Log.note(this.#inner.log, _32); @@ -132,9 +128,9 @@ export class sumFuture { const _47: rt.u64 = this.#total; rt.drop(this.#inner); unwind = 34; - rt.drop(this.#guard$2); + rt.drop(this.#guard); unwind = 35; - rt.drop(this.#rx$2); + rt.drop(this.#rx); this.#state = 1; return _47; } @@ -164,9 +160,9 @@ export class sumFuture { } rt.drop(this.#inner); } - rt.drop(this.#guard$2); + rt.drop(this.#guard); } - rt.drop(this.#rx$2); + rt.drop(this.#rx); } this.#state = 2; throw e; @@ -191,9 +187,6 @@ export class blocksFuture { #rx: Consumer.Consumer; #guard: Guard.Guard; #moves: boolean; - #rx$2!: Consumer.Consumer; - #guard$2!: Guard.Guard; - #moves$2!: boolean; #first!: Guard.Guard; #second!: Guard.Guard; #waited!: rt.u64; @@ -282,12 +275,12 @@ export class blocksFuture { this.#saved$5 = false; if (this.#saved$3) { unwind = 62; - rt.drop(this.#guard$2); + rt.drop(this.#guard); } this.#saved$3 = false; if (this.#saved$6) { unwind = 0; - rt.drop(this.#rx$2); + rt.drop(this.#rx); } this.#saved$6 = false; } catch (e) { @@ -373,12 +366,12 @@ export class blocksFuture { } this.#saved$5 = false; if (this.#saved$3) { - rt.drop(this.#guard$2); + rt.drop(this.#guard); } } this.#saved$3 = false; if (this.#saved$6) { - rt.drop(this.#rx$2); + rt.drop(this.#rx); } this.#saved$6 = false; } @@ -407,24 +400,21 @@ export class blocksFuture { this.#saved$8 = false; this.#saved$7 = false; this.#saved$6 = true; - this.#rx$2 = this.#rx; this.#saved$3 = true; - this.#guard$2 = this.#guard; - this.#moves$2 = this.#moves; - this.#first = Guard.new(rt.u32Add(this.#guard$2.id, 200), Log.clone$Clone(this.#guard$2.log)); + this.#first = Guard.new(rt.u32Add(this.#guard.id, 200), Log.clone$Clone(this.#guard.log)); unwind = 131; this.#saved$5 = true; - this.#second = Guard.new(rt.u32Add(this.#guard$2.id, 300), Log.clone$Clone(this.#guard$2.log)); + this.#second = Guard.new(rt.u32Add(this.#guard.id, 300), Log.clone$Clone(this.#guard.log)); unwind = 142; this.#saved$4 = true; rt.drop(new blocksFuture$2(this.#first)); - turns(this.#guard$2.log, rt.u32Rem(this.#guard$2.id, 5)); - temporaries(this.#guard$2.log, this.#guard$2.id); + turns(this.#guard.log, rt.u32Rem(this.#guard.id, 5)); + temporaries(this.#guard.log, this.#guard.id); unwind = 130; - this.#saved = Guard.new(rt.u32Add(this.#guard$2.id, 900), Log.clone$Clone(this.#guard$2.log)); + this.#saved = Guard.new(rt.u32Add(this.#guard.id, 900), Log.clone$Clone(this.#guard.log)); unwind = 128; this.#saved$9 = true; - this.#awaitee = new recvFuture(this.#rx$2); + this.#awaitee = new recvFuture(this.#rx); } else if (this.#state === 1) { rt.asyncFnResumed(); } else if (this.#state === 2) { @@ -451,15 +441,15 @@ export class blocksFuture { this.#waited = consume(this.#saved, result); unwind = 142; this.#saved$9 = false; - _40 = Guard.new(rt.u32Add(this.#guard$2.id, 910), Log.clone$Clone(this.#guard$2.log)); + _40 = Guard.new(rt.u32Add(this.#guard.id, 910), Log.clone$Clone(this.#guard.log)); unwind = 124; - const _46: Guard.Guard = Guard.new(rt.u32Add(this.#guard$2.id, 920), Log.clone$Clone(this.#guard$2.log)); + const _46: Guard.Guard = Guard.new(rt.u32Add(this.#guard.id, 920), Log.clone$Clone(this.#guard.log)); unwind = 122; this.#slots = [_40, _46]; - this.#saved = Guard.new(rt.u32Add(this.#guard$2.id, 930), Log.clone$Clone(this.#guard$2.log)); + this.#saved = Guard.new(rt.u32Add(this.#guard.id, 930), Log.clone$Clone(this.#guard.log)); unwind = 120; this.#saved$8 = true; - this.#awaitee$2 = new slotFuture(this.#rx$2, this.#slots.length); + this.#awaitee$2 = new slotFuture(this.#rx, this.#slots.length); } else { this.#state = 3; return rt.Pending; @@ -486,11 +476,11 @@ export class blocksFuture { unwind = 117; Guard.note(this.#slots[0], _78); unwind = 137; - this.#tally = { n: this.#guard$2.id }; + this.#tally = { n: this.#guard.id }; this.#saved$7 = true; seen = new blocksFuture$3(copy$Tally(this.#tally)); this.#tally.n = rt.u32Add(this.#tally.n, 1000); - this.#saved = this.#guard$2; + this.#saved = this.#guard; this.#saved$2 = this.#tally.n; this.#saved$7 = false; this.#awaitee$3 = seen; @@ -530,30 +520,30 @@ export class blocksFuture { const args6: rt.Fmt[] = [_136, (f: rt.Formatter) => rt.u32Display(arg4, f)]; const _129: string = rt.fmtFormat(["mark ", args6[0], " ", args6[1]]); unwind = 112; - Guard.note(this.#guard$2, _129); + Guard.note(this.#guard, _129); unwind = 111; _141 = undefined; - const _142: Guard.Guard = Guard.new(rt.u32Add(this.#guard$2.id, 800), Log.clone$Clone(this.#guard$2.log)); + const _142: Guard.Guard = Guard.new(rt.u32Add(this.#guard.id, 800), Log.clone$Clone(this.#guard.log)); unwind = 137; const _149: Outer.Outer = new Outer.Outer({ inner: _141, guard: _142 }); unwind = 110; this.#nested = new Inner.Inner({ outer: _149 }); - const third: Guard.Guard = Guard.new(rt.u32Add(this.#guard$2.id, 400), Log.clone$Clone(this.#guard$2.log)); - if (!this.#moves$2) { + const third: Guard.Guard = Guard.new(rt.u32Add(this.#guard.id, 400), Log.clone$Clone(this.#guard.log)); + if (!this.#moves) { this.#saved = third; } else { this.#saved = third; } unwind = 109; Guard.note(this.#saved, "chosen"); - if (this.#moves$2) { + if (this.#moves) { this.#saved$3 = false; - rt.drop(new blocksFuture$5(this.#guard$2)); + rt.drop(new blocksFuture$5(this.#guard)); } this.#saved$5 = false; this.#saved$4 = false; this.#saved$6 = false; - this.#awaitee$4 = new blocksFuture$6(this.#first, this.#second, this.#rx$2); + this.#awaitee$4 = new blocksFuture$6(this.#first, this.#second, this.#rx); } else { this.#state = 6; return rt.Pending; @@ -576,7 +566,7 @@ export class blocksFuture { this.#saved$5 = false; if (this.#saved$3) { unwind = 133; - rt.drop(this.#guard$2); + rt.drop(this.#guard); } this.#saved$3 = false; this.#saved$6 = false; @@ -717,12 +707,12 @@ export class blocksFuture { } this.#saved$5 = false; if (this.#saved$3) { - rt.drop(this.#guard$2); + rt.drop(this.#guard); } } this.#saved$3 = false; if (this.#saved$6) { - rt.drop(this.#rx$2); + rt.drop(this.#rx); } this.#saved$6 = false; this.#state = 2; @@ -1029,7 +1019,6 @@ export class slotFuture { #state: number = 0; #_constructor: Consumer.Consumer; #eval: rt.usize; - #eval$2!: rt.usize; #awaitee!: rt.Future; constructor(_constructor: Consumer.Consumer, eval_: rt.usize) { @@ -1049,9 +1038,7 @@ export class slotFuture { try { if (this.#state === 0) { unwind = 16; - const constructor: Consumer.Consumer = this.#_constructor; - this.#eval$2 = this.#eval; - this.#awaitee = new recvFuture(constructor); + this.#awaitee = new recvFuture(this.#_constructor); } else if (this.#state === 1) { rt.asyncFnResumed(); } else if (this.#state === 2) { @@ -1066,7 +1053,7 @@ export class slotFuture { if (result === undefined) { _19 = 0; } else { - _19 = rt.usizeRem(rt.u64Low(result), this.#eval$2); + _19 = rt.usizeRem(rt.u64Low(result), this.#eval); } this.#state = 1; return _19; @@ -1499,8 +1486,6 @@ export class drainFuture { #state: number = 0; #rx: Consumer.Consumer; #depth: rt.u32; - #rx$2!: Consumer.Consumer; - #depth$2!: rt.u32; #total!: rt.u64; #awaitee!: rt.Future; @@ -1529,12 +1514,12 @@ export class drainFuture { return; } unwind = 0; - rt.drop(this.#rx$2); + rt.drop(this.#rx); } catch (e) { if (unwind === 0) { throw e; } - rt.drop(this.#rx$2); + rt.drop(this.#rx); throw e; } } @@ -1548,8 +1533,6 @@ export class drainFuture { switch (bb0) { case 0: if (this.#state === 0) { - this.#rx$2 = this.#rx; - this.#depth$2 = this.#depth; this.#total = 0; bb0 = 1; continue; @@ -1571,20 +1554,20 @@ export class drainFuture { continue; } case 1: - if (this.#depth$2 === 1) { + if (this.#depth === 1) { unwind = 36; - this.#awaitee = new recvFuture(this.#rx$2); + this.#awaitee = new recvFuture(this.#rx); bb0 = 7; continue; } - if (this.#depth$2 === 4) { + if (this.#depth === 4) { unwind = 36; - this.#awaitee = new level3Future(this.#rx$2); + this.#awaitee = new level3Future(this.#rx); bb0 = 15; continue; } unwind = 36; - this.#awaitee = new level15Future(this.#rx$2); + this.#awaitee = new level15Future(this.#rx); bb0 = 22; continue; case 22: @@ -1627,7 +1610,7 @@ export class drainFuture { if (next === undefined) { unwind = 37; const _40: rt.u64 = this.#total; - rt.drop(this.#rx$2); + rt.drop(this.#rx); this.#state = 1; return _40; } @@ -1650,7 +1633,7 @@ export class drainFuture { } else if (unwind !== 36) { break b1; } - rt.drop(this.#rx$2); + rt.drop(this.#rx); } this.#state = 2; throw e; diff --git a/ts/src/lower/mir/coroutine.rs b/ts/src/lower/mir/coroutine.rs index a1474099a..3a48def82 100644 --- a/ts/src/lower/mir/coroutine.rs +++ b/ts/src/lower/mir/coroutine.rs @@ -4,9 +4,10 @@ //! transform made, which drops what the state it is in holds. use rustc_abi::{FieldIdx, VariantIdx}; +use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::DefId; use rustc_index::IndexVec; -use rustc_middle::mir::{CoroutineSavedLocal, Operand}; +use rustc_middle::mir::{self, CoroutineSavedLocal, Operand}; use rustc_middle::ty::{self, EarlyBinder, GenericArgsRef, Instance}; use rustc_span::Span; @@ -106,11 +107,21 @@ pub fn info<'tcx>(t: &mut Translator<'_, 'tcx>, def_id: DefId, args: GenericArgs }; } }; + let resume = super::instance_mir(t, instance, span); + let moved = resume + .as_ref() + .map(|mir| moved_upvars(mir, def_id, layout)) + .unwrap_or_default(); let mut saved = IndexVec::new(); // Locals of one type that are never live at once share a field, as rustc overlaps // them in memory: each `.await` of a future of one type keeps it in the same one. let mut shared: Vec<(FieldId, Type, Vec)> = Vec::new(); for (local, field) in layout.field_tys.iter_enumerated() { + // An argument the body moves into its own variable keeps its field. + if let Some(&upvar) = moved.get(&local) { + saved.push(upvars[upvar]); + continue; + } let ty = t.subst(args, field.ty); // A local held across an `.await`, refused as any variable is. let ty = t.held_ty(ty, field.source_info.span); @@ -171,7 +182,7 @@ pub fn info<'tcx>(t: &mut Translator<'_, 'tcx>, def_id: DefId, args: GenericArgs name: String::new(), alias: None, }); - if let Some(mir) = super::instance_mir(t, instance, span) { + if let Some(mir) = resume { let ret = mir.return_ty(); let mut b = Body::new(t, args); let mut fx = Fx::new(&mut b, &mir, Env::Coroutine, span); @@ -278,3 +289,78 @@ pub fn construct<'tcx>( let values = ops.iter().map(|op| fx.operand(op, span, out)).collect(); Expr::New(Box::new(Expr::Sym(info.sym)), values) } + +/// The saved locals the resume function `mir` of the coroutine `def_id` moves or copies +/// an upvar into, with the upvar's index, where that is the upvar's one read: nothing +/// reads the upvar's field after, so the local can keep its value there. +fn moved_upvars<'tcx>( + mir: &mir::Body<'tcx>, + def_id: DefId, + layout: &mir::CoroutineLayout<'tcx>, +) -> FxHashMap { + use mir::visit::{PlaceContext, Visitor}; + use mir::{ProjectionElem, Rvalue, StatementKind}; + + struct Reads<'m, 'tcx> { + mir: &'m mir::Body<'tcx>, + def_id: DefId, + reads: FxHashMap, + } + impl<'tcx> Reads<'_, 'tcx> { + /// The upvar `place` is, or the field of a variant, of this coroutine. + fn split(&self, place: mir::Place<'tcx>) -> Option<(Option, FieldIdx)> { + let ty = self.mir.local_decls[place.local].ty.builtin_deref(true)?; + if !matches!(ty.kind(), ty::Coroutine(d, _) if *d == self.def_id) { + return None; + } + match place.projection.as_slice() { + [ProjectionElem::Deref, ProjectionElem::Field(f, _), ..] => Some((None, *f)), + [ + ProjectionElem::Deref, + ProjectionElem::Downcast(_, v), + ProjectionElem::Field(f, _), + .., + ] => Some((Some(*v), *f)), + _ => None, + } + } + } + impl<'tcx> Visitor<'tcx> for Reads<'_, 'tcx> { + fn visit_place(&mut self, place: &mir::Place<'tcx>, cx: PlaceContext, at: mir::Location) { + // Debug info names a place without reading it. + if !matches!(cx, PlaceContext::NonUse(_)) + && let Some((None, f)) = self.split(*place) + { + *self.reads.entry(f).or_default() += 1; + } + self.super_place(place, cx, at); + } + } + + let mut reads = Reads { + mir, + def_id, + reads: FxHashMap::default(), + }; + reads.visit_body(mir); + let mut moved = FxHashMap::default(); + for data in mir.basic_blocks.iter() { + for stmt in &data.statements { + let StatementKind::Assign(assign) = &stmt.kind else { + continue; + }; + let (dest, Rvalue::Use(Operand::Move(src) | Operand::Copy(src), _)) = &**assign else { + continue; + }; + if src.projection.len() == 2 + && dest.projection.len() == 3 + && let Some((None, upvar)) = reads.split(*src) + && let Some((Some(variant), field)) = reads.split(*dest) + && reads.reads.get(&upvar) == Some(&1) + { + moved.insert(layout.variant_fields[variant][field], upvar.index()); + } + } + } + moved +} diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index ed20f593b..3ecfa051b 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -2947,10 +2947,11 @@ fn fails(term: &mir::Terminator<'_>) -> bool { c.const_.try_to_bool().is_some_and(|b| b != *expected) } -/// Drop the assignments of a variable to itself, which ferrying a value through -/// temporaries leaves. +/// Drop the assignments of a variable or a field to itself, which ferrying a value +/// through temporaries leaves, as does a coroutine moving its argument into the +/// variable that keeps its field. fn drop_self_assignments(stmts: &mut Vec) { - stmts.retain(|s| !matches!(&s.kind, StmtKind::Expr(Expr::Assign(t, v)) if matches!((&**t, &**v), (Expr::Ident(a), Expr::Ident(b)) if a == b))); + stmts.retain(|s| !matches!(&s.kind, StmtKind::Expr(Expr::Assign(t, v)) if same_path(t, v))); for stmt in stmts.iter_mut() { match &mut stmt.kind { StmtKind::If { then, els, .. } => { @@ -2973,6 +2974,23 @@ fn drop_self_assignments(stmts: &mut Vec) { } } +/// Whether `a` and `b` are one path: a variable, `this`, or a property of one. +fn same_path(a: &Expr, b: &Expr) -> bool { + match (a, b) { + (Expr::Ident(a), Expr::Ident(b)) => a == b, + (Expr::This, Expr::This) => true, + (Expr::Member(a, ka), Expr::Member(b, kb)) => { + let key = match (ka, kb) { + (ts::Key::Name(x), ts::Key::Name(y)) => x == y, + (ts::Key::Field(x), ts::Key::Field(y)) => x == y, + _ => false, + }; + key && same_path(a, b) + } + _ => false, + } +} + /// Return values in place throughout `stmts`, given the names cleanups read. fn return_in_place(stmts: &mut Vec, caught: &FxHashSet) { sink_return(stmts); From d719cb553fda78a666ba203b014bf2d33510f263 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:34:33 -0700 Subject: [PATCH 05/15] feat(ts): give 64- and 128-bit sums their own functions A bundle with only 64-bit sums, like the async handoff's u64Add, no longer pulls in the 128-bit limbs. sum64 reads halves without boxing a number into limbs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/runtime/rt/int.ts | 142 ++++++++++++++++++++----------------------- 1 file changed, 65 insertions(+), 77 deletions(-) diff --git a/ts/runtime/rt/int.ts b/ts/runtime/rt/int.ts index 716cffbf2..adac30886 100644 --- a/ts/runtime/rt/int.ts +++ b/ts/runtime/rt/int.ts @@ -674,25 +674,28 @@ function mul32(a: number, b: number): number { return (((mid & 0xffff) << 16) | (p00 & 0xffff)) >>> 0; } -// Which way the last `sum` left the type's range: 1 past its maximum, -1 below its +// Which way the last sum left the type's range: 1 past its maximum, -1 below its // minimum, and 0 not at all. let overflow = 0; -/** - * `a + b`, or `a - b` if `sign` is -1, wrapped into the type's range, setting `overflow`. - * Each limb's carry or borrow is the floor of its sum over 2^32. - */ -function sum(a: Wide, b: Wide, sign: number, bits: number, signed: boolean): Wide { - const x = limbs(a, bits, signed); - const y = limbs(b, bits, signed); +// A sum of each width is its own function, so a bundle of 64-bit sums leaves out the +// 128-bit limbs. Each limb's carry or borrow is the floor of its sum over 2^32. + +/** A 64-bit `a + b`, or `a - b` if `sign` is -1, wrapped into the type's range, setting `overflow`. */ +function sum64(a: Wide, b: Wide, sign: number, signed: boolean): Wide { + const lo = loOf(a) + sign * loOf(b); + const hi = hiOf(a) + sign * hiOf(b) + Math.floor(lo / TWO32); + overflow = outside(hi, signed); + return join(high(hi, signed), lo >>> 0); +} + +/** A 128-bit `a + b`, or `a - b` if `sign` is -1, wrapped into the type's range, setting `overflow`. */ +function sum128(a: Wide, b: Wide, sign: number, signed: boolean): Wide { + const x = limbs(a, 128, signed) as U128Limbs; + const y = limbs(b, 128, signed) as U128Limbs; const lo = x.lo + sign * y.lo; - if (bits === 64) { - const hi = x.hi + sign * y.hi + Math.floor(lo / TWO32); - overflow = outside(hi, signed); - return join(high(hi, signed), lo >>> 0); - } - const w1 = (x as U128Limbs).w1 + sign * (y as U128Limbs).w1 + Math.floor(lo / TWO32); - const w2 = (x as U128Limbs).w2 + sign * (y as U128Limbs).w2 + Math.floor(w1 / TWO32); + const w1 = x.w1 + sign * y.w1 + Math.floor(lo / TWO32); + const w2 = x.w2 + sign * y.w2 + Math.floor(w1 / TWO32); const hi = x.hi + sign * y.hi + Math.floor(w2 / TWO32); overflow = outside(hi, signed); return one({ hi: high(hi, signed), w2: w2 >>> 0, w1: w1 >>> 0, lo: lo >>> 0 } as Limbs); @@ -711,27 +714,19 @@ function extreme(top: boolean, bits: number, signed: boolean): Wide { return (bits === 64 ? { hi, lo: rest } : { hi, w2: rest, w1: rest, lo: rest }) as Limbs; } -function add(a: Wide, b: Wide, bits: number, signed: boolean): Wide { - const v = sum(a, b, 1, bits, signed); - if (overflow !== 0) panic("attempt to add with overflow"); - return v; -} - -function sub(a: Wide, b: Wide, bits: number, signed: boolean): Wide { - const v = sum(a, b, -1, bits, signed); - if (overflow !== 0) panic("attempt to subtract with overflow"); +/** The last sum, `v`, or a panic naming `op` if it overflowed. */ +function strict(v: Wide, op: string): Wide { + if (overflow !== 0) panic(`attempt to ${op} with overflow`); return v; } -/** `a + b`, or `a - b` if `sign` is -1, or `undefined` past the type's range. */ -function checkedSum(a: Wide, b: Wide, sign: number, bits: number, signed: boolean): Wide | undefined { - const v = sum(a, b, sign, bits, signed); +/** The last sum, `v`, or `undefined` if it overflowed. */ +function optional(v: Wide): Wide | undefined { return overflow === 0 ? v : undefined; } -/** `a + b`, or `a - b` if `sign` is -1, clamped to the type's range. */ -function saturatingSum(a: Wide, b: Wide, sign: number, bits: number, signed: boolean): Wide { - const v = sum(a, b, sign, bits, signed); +/** The last sum, `v`, clamped to the type's range. */ +function saturated(v: Wide, bits: number, signed: boolean): Wide { return overflow === 0 ? v : extreme(overflow > 0, bits, signed); } @@ -882,12 +877,6 @@ function divideWords(a: Limbs, b: number, bits: number, signed: boolean, remaind return one({ hi: high(words[0], signed), w2: words[1], w1: words[2], lo: words[3] } as Limbs); } -function neg(a: Wide, bits: number, signed: boolean): Wide { - const v = sum(0, a, -1, bits, signed); - if (overflow !== 0) panic("attempt to negate with overflow"); - return v; -} - function shl(a: Wide, b: number | Limbs, bits: number, signed: boolean): Wide { const n = shift(b, bits, "left"); if (typeof a === "number" && safe(a * 2 ** n)) return a * 2 ** n; @@ -1048,16 +1037,15 @@ function eq(a: Wide, b: Wide): boolean { return a === b || (typeof a !== "number" && typeof b !== "number" && compare(a, b) === 0); } -/** `Step` of a wide type, through its wrapping sum. */ -function wideStep(n: Wide, by: number, bits: number, signed: boolean): [Wide, boolean] { - const v = sum(n, Math.abs(by), by < 0 ? -1 : 1, bits, signed); +/** `Step`'s result from the last sum, `v`, which moved by `by`'s magnitude. */ +function stepped(v: Wide): [Wide, boolean] { return [v, overflow !== 0]; } /** `u64`'s `a + b`, panicking on overflow. */ -export const u64Add = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : add(a, b, 64, false)) as u64; +export const u64Add = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : strict(sum64(a, b, 1, false), "add")) as u64; /** `u64`'s `a - b`, panicking on overflow. */ -export const u64Sub = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : sub(a, b, 64, false)) as u64; +export const u64Sub = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : strict(sum64(a, b, -1, false), "subtract")) as u64; /** `u64`'s `a * b`, panicking on overflow. */ export const u64Mul = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && safe(a * b) ? a * b + 0 : mul(a, b, 64, false)) as u64; /** `u64`'s `a / b`, truncated, panicking on a zero divisor or overflow. */ @@ -1086,19 +1074,19 @@ export const u64Xor = (a: u64, b: u64): u64 => { /** `u64`'s `!a`. */ export const u64Not = (a: u64): u64 => not(a, 64, false) as u64; /** `u64`'s `checked_add`: `a + b`, or `undefined` on overflow. */ -export const u64CheckedAdd = (a: u64, b: u64): u64 | undefined => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : checkedSum(a, b, 1, 64, false)) as u64 | undefined; +export const u64CheckedAdd = (a: u64, b: u64): u64 | undefined => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : optional(sum64(a, b, 1, false))) as u64 | undefined; /** `u64`'s `checked_sub`: `a - b`, or `undefined` on overflow. */ -export const u64CheckedSub = (a: u64, b: u64): u64 | undefined => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : checkedSum(a, b, -1, 64, false)) as u64 | undefined; +export const u64CheckedSub = (a: u64, b: u64): u64 | undefined => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : optional(sum64(a, b, -1, false))) as u64 | undefined; /** `u64`'s `checked_mul`: `a * b`, or `undefined` on overflow. */ export const u64CheckedMul = (a: u64, b: u64): u64 | undefined => product(a, b, 64, false) as u64 | undefined; /** `u64`'s `saturating_add`: `a + b`, clamped to the type's range. */ -export const u64SaturatingAdd = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : saturatingSum(a, b, 1, 64, false)) as u64; +export const u64SaturatingAdd = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : saturated(sum64(a, b, 1, false), 64, false)) as u64; /** `u64`'s `saturating_sub`: `a - b`, clamped to the type's range. */ -export const u64SaturatingSub = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : saturatingSum(a, b, -1, 64, false)) as u64; +export const u64SaturatingSub = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : saturated(sum64(a, b, -1, false), 64, false)) as u64; /** `u64`'s `wrapping_add`: `a + b`, wrapped into the type's range. */ -export const u64WrappingAdd = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : sum(a, b, 1, 64, false)) as u64; +export const u64WrappingAdd = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : sum64(a, b, 1, false)) as u64; /** `u64`'s `wrapping_sub`: `a - b`, wrapped into the type's range. */ -export const u64WrappingSub = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : sum(a, b, -1, 64, false)) as u64; +export const u64WrappingSub = (a: u64, b: u64): u64 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : sum64(a, b, -1, false)) as u64; /** `u64`'s `leading_ones`: the count of leading one bits. */ export const u64LeadingOnes = (a: u64): number => leadingOnes(a, 64, false); /** `u64`'s `leading_zeros`: the count of leading zero bits. */ @@ -1140,12 +1128,12 @@ export const u64Max = (a: u64, b: u64): u64 => (lt(b, a) ? a : b); /** `u64`'s `Ord::min`: the lesser, `a` if they are equal. */ export const u64Min = (a: u64, b: u64): u64 => (lt(b, a) ? b : a); /** `u64`'s `Step`, which ranges step by: `n` moved by `by`, and whether that overflowed. */ -export const u64Step: Step = (n, by) => wideStep(n, by, 64, false) as [u64, boolean]; +export const u64Step: Step = (n, by) => stepped(sum64(n, Math.abs(by), by < 0 ? -1 : 1, false)) as [u64, boolean]; /** `i64`'s `a + b`, panicking on overflow. */ -export const i64Add = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : add(a, b, 64, true)) as i64; +export const i64Add = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : strict(sum64(a, b, 1, true), "add")) as i64; /** `i64`'s `a - b`, panicking on overflow. */ -export const i64Sub = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : sub(a, b, 64, true)) as i64; +export const i64Sub = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : strict(sum64(a, b, -1, true), "subtract")) as i64; /** `i64`'s `a * b`, panicking on overflow. */ export const i64Mul = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && safe(a * b) ? a * b + 0 : mul(a, b, 64, true)) as i64; /** `i64`'s `a / b`, truncated, panicking on a zero divisor or overflow. */ @@ -1153,7 +1141,7 @@ export const i64Div = (a: i64, b: i64): i64 => (typeof a === "number" && typeof /** `i64`'s `a % b`, panicking on a zero divisor or overflow. */ export const i64Rem = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && b !== 0 ? (a % b) + 0 : rem(a, b, 64, true)) as i64; /** `i64`'s `-a`, panicking on overflow. */ -export const i64Neg = (a: i64): i64 => (typeof a === "number" ? -a + 0 : neg(a, 64, true)) as i64; +export const i64Neg = (a: i64): i64 => (typeof a === "number" ? -a + 0 : strict(sum64(0, a, -1, true), "negate")) as i64; /** `i64`'s `a << b`, panicking on a shift by the width or more. */ export const i64Shl = (a: i64, b: number | Limbs): i64 => (typeof a === "number" && typeof b === "number" && b >= 0 && b < 64 && safe(a * 2 ** b) ? a * 2 ** b : shl(a, b, 64, true)) as i64; /** `i64`'s `a >> b`, panicking on a shift by the width or more. */ @@ -1176,19 +1164,19 @@ export const i64Xor = (a: i64, b: i64): i64 => { /** `i64`'s `!a`. */ export const i64Not = (a: i64): i64 => not(a, 64, true) as i64; /** `i64`'s `checked_add`: `a + b`, or `undefined` on overflow. */ -export const i64CheckedAdd = (a: i64, b: i64): i64 | undefined => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : checkedSum(a, b, 1, 64, true)) as i64 | undefined; +export const i64CheckedAdd = (a: i64, b: i64): i64 | undefined => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : optional(sum64(a, b, 1, true))) as i64 | undefined; /** `i64`'s `checked_sub`: `a - b`, or `undefined` on overflow. */ -export const i64CheckedSub = (a: i64, b: i64): i64 | undefined => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : checkedSum(a, b, -1, 64, true)) as i64 | undefined; +export const i64CheckedSub = (a: i64, b: i64): i64 | undefined => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : optional(sum64(a, b, -1, true))) as i64 | undefined; /** `i64`'s `checked_mul`: `a * b`, or `undefined` on overflow. */ export const i64CheckedMul = (a: i64, b: i64): i64 | undefined => product(a, b, 64, true) as i64 | undefined; /** `i64`'s `saturating_add`: `a + b`, clamped to the type's range. */ -export const i64SaturatingAdd = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : saturatingSum(a, b, 1, 64, true)) as i64; +export const i64SaturatingAdd = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : saturated(sum64(a, b, 1, true), 64, true)) as i64; /** `i64`'s `saturating_sub`: `a - b`, clamped to the type's range. */ -export const i64SaturatingSub = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : saturatingSum(a, b, -1, 64, true)) as i64; +export const i64SaturatingSub = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : saturated(sum64(a, b, -1, true), 64, true)) as i64; /** `i64`'s `wrapping_add`: `a + b`, wrapped into the type's range. */ -export const i64WrappingAdd = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : sum(a, b, 1, 64, true)) as i64; +export const i64WrappingAdd = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : sum64(a, b, 1, true)) as i64; /** `i64`'s `wrapping_sub`: `a - b`, wrapped into the type's range. */ -export const i64WrappingSub = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : sum(a, b, -1, 64, true)) as i64; +export const i64WrappingSub = (a: i64, b: i64): i64 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : sum64(a, b, -1, true)) as i64; /** `i64`'s `leading_ones`: the count of leading one bits. */ export const i64LeadingOnes = (a: i64): number => leadingOnes(a, 64, true); /** `i64`'s `leading_zeros`: the count of leading zero bits. */ @@ -1228,12 +1216,12 @@ export const i64Max = (a: i64, b: i64): i64 => (lt(b, a) ? a : b); /** `i64`'s `Ord::min`: the lesser, `a` if they are equal. */ export const i64Min = (a: i64, b: i64): i64 => (lt(b, a) ? b : a); /** `i64`'s `Step`, which ranges step by: `n` moved by `by`, and whether that overflowed. */ -export const i64Step: Step = (n, by) => wideStep(n, by, 64, true) as [i64, boolean]; +export const i64Step: Step = (n, by) => stepped(sum64(n, Math.abs(by), by < 0 ? -1 : 1, true)) as [i64, boolean]; /** `u128`'s `a + b`, panicking on overflow. */ -export const u128Add = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : add(a, b, 128, false)) as u128; +export const u128Add = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : strict(sum128(a, b, 1, false), "add")) as u128; /** `u128`'s `a - b`, panicking on overflow. */ -export const u128Sub = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : sub(a, b, 128, false)) as u128; +export const u128Sub = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : strict(sum128(a, b, -1, false), "subtract")) as u128; /** `u128`'s `a * b`, panicking on overflow. */ export const u128Mul = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && safe(a * b) ? a * b + 0 : mul(a, b, 128, false)) as u128; /** `u128`'s `a / b`, truncated, panicking on a zero divisor or overflow. */ @@ -1262,19 +1250,19 @@ export const u128Xor = (a: u128, b: u128): u128 => { /** `u128`'s `!a`. */ export const u128Not = (a: u128): u128 => not(a, 128, false) as u128; /** `u128`'s `checked_add`: `a + b`, or `undefined` on overflow. */ -export const u128CheckedAdd = (a: u128, b: u128): u128 | undefined => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : checkedSum(a, b, 1, 128, false)) as u128 | undefined; +export const u128CheckedAdd = (a: u128, b: u128): u128 | undefined => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : optional(sum128(a, b, 1, false))) as u128 | undefined; /** `u128`'s `checked_sub`: `a - b`, or `undefined` on overflow. */ -export const u128CheckedSub = (a: u128, b: u128): u128 | undefined => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : checkedSum(a, b, -1, 128, false)) as u128 | undefined; +export const u128CheckedSub = (a: u128, b: u128): u128 | undefined => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : optional(sum128(a, b, -1, false))) as u128 | undefined; /** `u128`'s `checked_mul`: `a * b`, or `undefined` on overflow. */ export const u128CheckedMul = (a: u128, b: u128): u128 | undefined => product(a, b, 128, false) as u128 | undefined; /** `u128`'s `saturating_add`: `a + b`, clamped to the type's range. */ -export const u128SaturatingAdd = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : saturatingSum(a, b, 1, 128, false)) as u128; +export const u128SaturatingAdd = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : saturated(sum128(a, b, 1, false), 128, false)) as u128; /** `u128`'s `saturating_sub`: `a - b`, clamped to the type's range. */ -export const u128SaturatingSub = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : saturatingSum(a, b, -1, 128, false)) as u128; +export const u128SaturatingSub = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : saturated(sum128(a, b, -1, false), 128, false)) as u128; /** `u128`'s `wrapping_add`: `a + b`, wrapped into the type's range. */ -export const u128WrappingAdd = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : sum(a, b, 1, 128, false)) as u128; +export const u128WrappingAdd = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a + b, false) ? a + b : sum128(a, b, 1, false)) as u128; /** `u128`'s `wrapping_sub`: `a - b`, wrapped into the type's range. */ -export const u128WrappingSub = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : sum(a, b, -1, 128, false)) as u128; +export const u128WrappingSub = (a: u128, b: u128): u128 => (typeof a === "number" && typeof b === "number" && fits(a - b, false) ? a - b : sum128(a, b, -1, false)) as u128; /** `u128`'s `leading_ones`: the count of leading one bits. */ export const u128LeadingOnes = (a: u128): number => leadingOnes(a, 128, false); /** `u128`'s `leading_zeros`: the count of leading zero bits. */ @@ -1314,12 +1302,12 @@ export const u128Max = (a: u128, b: u128): u128 => (lt(b, a) ? a : b); /** `u128`'s `Ord::min`: the lesser, `a` if they are equal. */ export const u128Min = (a: u128, b: u128): u128 => (lt(b, a) ? b : a); /** `u128`'s `Step`, which ranges step by: `n` moved by `by`, and whether that overflowed. */ -export const u128Step: Step = (n, by) => wideStep(n, by, 128, false) as [u128, boolean]; +export const u128Step: Step = (n, by) => stepped(sum128(n, Math.abs(by), by < 0 ? -1 : 1, false)) as [u128, boolean]; /** `i128`'s `a + b`, panicking on overflow. */ -export const i128Add = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : add(a, b, 128, true)) as i128; +export const i128Add = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : strict(sum128(a, b, 1, true), "add")) as i128; /** `i128`'s `a - b`, panicking on overflow. */ -export const i128Sub = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : sub(a, b, 128, true)) as i128; +export const i128Sub = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : strict(sum128(a, b, -1, true), "subtract")) as i128; /** `i128`'s `a * b`, panicking on overflow. */ export const i128Mul = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && safe(a * b) ? a * b + 0 : mul(a, b, 128, true)) as i128; /** `i128`'s `a / b`, truncated, panicking on a zero divisor or overflow. */ @@ -1327,7 +1315,7 @@ export const i128Div = (a: i128, b: i128): i128 => (typeof a === "number" && typ /** `i128`'s `a % b`, panicking on a zero divisor or overflow. */ export const i128Rem = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && b !== 0 ? (a % b) + 0 : rem(a, b, 128, true)) as i128; /** `i128`'s `-a`, panicking on overflow. */ -export const i128Neg = (a: i128): i128 => (typeof a === "number" ? -a + 0 : neg(a, 128, true)) as i128; +export const i128Neg = (a: i128): i128 => (typeof a === "number" ? -a + 0 : strict(sum128(0, a, -1, true), "negate")) as i128; /** `i128`'s `a << b`, panicking on a shift by the width or more. */ export const i128Shl = (a: i128, b: number | Limbs): i128 => (typeof a === "number" && typeof b === "number" && b >= 0 && b < 128 && safe(a * 2 ** b) ? a * 2 ** b : shl(a, b, 128, true)) as i128; /** `i128`'s `a >> b`, panicking on a shift by the width or more. */ @@ -1350,19 +1338,19 @@ export const i128Xor = (a: i128, b: i128): i128 => { /** `i128`'s `!a`. */ export const i128Not = (a: i128): i128 => not(a, 128, true) as i128; /** `i128`'s `checked_add`: `a + b`, or `undefined` on overflow. */ -export const i128CheckedAdd = (a: i128, b: i128): i128 | undefined => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : checkedSum(a, b, 1, 128, true)) as i128 | undefined; +export const i128CheckedAdd = (a: i128, b: i128): i128 | undefined => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : optional(sum128(a, b, 1, true))) as i128 | undefined; /** `i128`'s `checked_sub`: `a - b`, or `undefined` on overflow. */ -export const i128CheckedSub = (a: i128, b: i128): i128 | undefined => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : checkedSum(a, b, -1, 128, true)) as i128 | undefined; +export const i128CheckedSub = (a: i128, b: i128): i128 | undefined => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : optional(sum128(a, b, -1, true))) as i128 | undefined; /** `i128`'s `checked_mul`: `a * b`, or `undefined` on overflow. */ export const i128CheckedMul = (a: i128, b: i128): i128 | undefined => product(a, b, 128, true) as i128 | undefined; /** `i128`'s `saturating_add`: `a + b`, clamped to the type's range. */ -export const i128SaturatingAdd = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : saturatingSum(a, b, 1, 128, true)) as i128; +export const i128SaturatingAdd = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : saturated(sum128(a, b, 1, true), 128, true)) as i128; /** `i128`'s `saturating_sub`: `a - b`, clamped to the type's range. */ -export const i128SaturatingSub = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : saturatingSum(a, b, -1, 128, true)) as i128; +export const i128SaturatingSub = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : saturated(sum128(a, b, -1, true), 128, true)) as i128; /** `i128`'s `wrapping_add`: `a + b`, wrapped into the type's range. */ -export const i128WrappingAdd = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : sum(a, b, 1, 128, true)) as i128; +export const i128WrappingAdd = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a + b, true) ? a + b : sum128(a, b, 1, true)) as i128; /** `i128`'s `wrapping_sub`: `a - b`, wrapped into the type's range. */ -export const i128WrappingSub = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : sum(a, b, -1, 128, true)) as i128; +export const i128WrappingSub = (a: i128, b: i128): i128 => (typeof a === "number" && typeof b === "number" && fits(a - b, true) ? a - b : sum128(a, b, -1, true)) as i128; /** `i128`'s `leading_ones`: the count of leading one bits. */ export const i128LeadingOnes = (a: i128): number => leadingOnes(a, 128, true); /** `i128`'s `leading_zeros`: the count of leading zero bits. */ @@ -1402,4 +1390,4 @@ export const i128Max = (a: i128, b: i128): i128 => (lt(b, a) ? a : b); /** `i128`'s `Ord::min`: the lesser, `a` if they are equal. */ export const i128Min = (a: i128, b: i128): i128 => (lt(b, a) ? b : a); /** `i128`'s `Step`, which ranges step by: `n` moved by `by`, and whether that overflowed. */ -export const i128Step: Step = (n, by) => wideStep(n, by, 128, true) as [i128, boolean]; +export const i128Step: Step = (n, by) => stepped(sum128(n, Math.abs(by), by < 0 ? -1 : 1, true)) as [i128, boolean]; From 2187867f20969c822d947549649bf13475412612 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:12:03 -0700 Subject: [PATCH 06/15] fix(ts): keep stepped loops as while loops for-of over an array took Firefox 1.19x as long on the async handoff against the stepped loop (A/A 1.05), and Chrome no less time. Without it the handoff is 3440 bytes gzipped, under its 3458 target. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- .../codec/expected/coding/version.Versions.ts | 16 +- ts/fixtures/codec/expected/harness.ts | 17 +- ts/fixtures/lang/expected/chars.ts | 25 ++- ts/fixtures/lang/expected/collections.ts | 87 +++++++- ts/fixtures/lang/expected/fmt.ts | 8 +- ts/fixtures/lang/expected/iters.ts | 27 ++- ts/fixtures/lang/expected/shapes.ts | 78 ++++++- ts/fixtures/task/expected/kio.WaiterList.ts | 25 ++- ts/src/lower/mir/cfg.rs | 33 +-- ts/src/lower/mir/inline.rs | 22 +- ts/src/lower/mir/mod.rs | 32 +-- ts/src/lower/mir/step.rs | 191 ------------------ ts/src/print.rs | 24 +-- ts/src/ts.rs | 9 +- 14 files changed, 280 insertions(+), 314 deletions(-) diff --git a/ts/fixtures/codec/expected/coding/version.Versions.ts b/ts/fixtures/codec/expected/coding/version.Versions.ts index f1a961f65..35e75ebad 100644 --- a/ts/fixtures/codec/expected/coding/version.Versions.ts +++ b/ts/fixtures/codec/expected/coding/version.Versions.ts @@ -49,7 +49,13 @@ export function decode$Decode_Form(r: Decoder.Decoder, version: Form.Form): rt.R export function encode$Encode_Form(self: Versions, w: Encoder.Encoder, version: Form.Form): rt.Result { const _4: rt.Result = Encoder.varint(w, self._0.length as rt.u64); if (_4.ok) { - for (const _14 of self._0) { + const iterS: Version.Version[] = self._0; + let iterI: number = 0; + while (true) { + const _14: Version.Version | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_14 === rt.DONE) { + break; + } const _18: rt.Result = Version.encode$Encode_Form(_14, w, version); if (!_18.ok) { return _18; @@ -64,7 +70,13 @@ export function encode$Encode_Form(self: Versions, w: Encoder.Encoder, version: export function encode$Encode_Version(self: Versions, w: Encoder.Encoder, version: version_Version.Version): rt.Result { const _4: rt.Result = Encoder.varint(w, self._0.length as rt.u64); if (_4.ok) { - for (const _14 of self._0) { + const iterS: Version.Version[] = self._0; + let iterI: number = 0; + while (true) { + const _14: Version.Version | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_14 === rt.DONE) { + break; + } const _18: rt.Result = Version.encode$Encode_Version(_14, w, version); if (!_18.ok) { return _18; diff --git a/ts/fixtures/codec/expected/harness.ts b/ts/fixtures/codec/expected/harness.ts index 1efea3b26..1a3cc0f3d 100644 --- a/ts/fixtures/codec/expected/harness.ts +++ b/ts/fixtures/codec/expected/harness.ts @@ -200,7 +200,13 @@ export function decodeScript(data: Uint8Array, out: rt.ByteVec): void { if (_9 !== undefined) { const _13: [Uint8Array, Uint8Array] = rt.sliceSplitAt(_9[1], rt.min(_9[1].length, _9[0] as rt.usize)); const r: Decoder.Decoder = Decoder.new(_13[1], form(selector)); - for (const _21 of _13[0]) { + const iterS: Uint8Array = _13[0]; + let iterI: number = 0; + while (true) { + const _21: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_21 === rt.DONE) { + break; + } const _26: rt.Result = decodeStep(r, _21, out); if (_26.ok) { rt.byteVecPush(out, 0); @@ -318,7 +324,14 @@ export function encodeScript(data: Uint8Array, out: rt.ByteVec): void { const _20: Form.Form = form(selector); const w: Encoder.Encoder = Encoder.new(buf, _20); const prefixes: Prefix.Prefix[] = []; - for (const step of _13[0]) { + const iterS: Uint8Array = _13[0]; + let iterI: number = 0; + while (true) { + const _24: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_24 === rt.DONE) { + break; + } + const step: rt.u8 = _24; const _30: [rt.u64, Uint8Array] = takeU64(values); const value: rt.u64 = _30[0]; values = _30[1]; diff --git a/ts/fixtures/lang/expected/chars.ts b/ts/fixtures/lang/expected/chars.ts index d569e3a00..93828aeca 100644 --- a/ts/fixtures/lang/expected/chars.ts +++ b/ts/fixtures/lang/expected/chars.ts @@ -67,7 +67,13 @@ export function class_(c: rt.char): rt.u8 { export function chars(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _4: rt.u8 = rt.u8Rem(kind, 4); if (_4 === 0) { - for (const _10 of scalars(data)) { + const iterS: rt.u32[] = scalars(data); + let iterI: number = 0; + while (true) { + const _10: rt.u32 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_10 === rt.DONE) { + break; + } const _14: rt.char | undefined = rt.charFromU32(_10); if (_14 === undefined) { rt.byteVecPush(out, 255); @@ -78,7 +84,14 @@ export function chars(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } } } else if (_4 === 1) { - for (const n2 of scalars(data)) { + const iterS2: rt.u32[] = scalars(data); + let iterI2: number = 0; + while (true) { + const _27: rt.u32 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; + if (_27 === rt.DONE) { + break; + } + const n2: rt.u32 = _27; const c2: rt.char = rt.optionUnwrapOr(rt.charFromU32(n2), (n2 & 0xff) as rt.char); rt.byteVecPush(out, c2 & 0xff); rt.byteVecExtendFromSlice(out, rt.u16ToBeBytes(c2 & 0xffff)); @@ -118,7 +131,13 @@ export function chars(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(_128 as rt.u32)); } } else { - for (const _140 of scalars(data)) { + const iterS3: rt.u32[] = scalars(data); + let iterI3: number = 0; + while (true) { + const _140: rt.u32 | rt.Done = iterI3 < iterS3.length ? iterS3[iterI3++] : rt.DONE; + if (_140 === rt.DONE) { + break; + } const _144: rt.char | undefined = rt.charFromU32(_140); if (_144 !== undefined) { const arg = ([_144] as [rt.char])[0]; diff --git a/ts/fixtures/lang/expected/collections.ts b/ts/fixtures/lang/expected/collections.ts index 0d9b2a13d..361f58975 100644 --- a/ts/fixtures/lang/expected/collections.ts +++ b/ts/fixtures/lang/expected/collections.ts @@ -285,7 +285,14 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { return t14.n & 0xff; })); } - for (const b5 of data) { + const iterS: Uint8Array = data; + let iterI: number = 0; + while (true) { + const _380: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_380 === rt.DONE) { + break; + } + const b5: rt.u8 = _380; rt.byteVecPush(out, claim(copy2, rt.u8Rem(b5, 8), b5 as rt.u16)); } const stamped: rt.HashMap = rt.hashNew() as rt.HashMap; @@ -344,7 +351,14 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, rt.hashLen(tuples) & 0xff); } else { const words: rt.HashMap = rt.hashNew() as rt.HashMap; - for (const b6 of data) { + const iterS2: Uint8Array = data; + let iterI2: number = 0; + while (true) { + const _496: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; + if (_496 === rt.DONE) { + break; + } + const b6: rt.u8 = _496; const _502: rt.usize = rt.usizeRem(b6 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); if (!(_502 < 8)) { rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _502); @@ -451,7 +465,14 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { if (_4 === 0) { const hashed: rt.HashSet = rt.hashNew() as rt.HashSet; const sorted: rt.BTreeSet = rt.btreeNew(rt.cmp) as rt.BTreeSet; - for (const b of data) { + const iterS: Uint8Array = data; + let iterI: number = 0; + while (true) { + const _10: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_10 === rt.DONE) { + break; + } + const b: rt.u8 = _10; const v: rt.u16 = rt.u16Rem(b as rt.u16, 24); const _17: rt.u8 = rt.u8Rem(b, 3); if (_17 === 0) { @@ -493,7 +514,14 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_4 === 1) { const nibbles: rt.BTreeSet = rt.btreeNew(Nibble.cmp$Ord) as rt.BTreeSet; const seen: rt.HashSet = rt.hashNew(rt.hashing(Nibble.hash$Hash_DefaultHasher, Nibble.eq$PartialEq)) as rt.HashSet; - for (const b2 of data) { + const iterS2: Uint8Array = data; + let iterI2: number = 0; + while (true) { + const _106: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; + if (_106 === rt.DONE) { + break; + } + const b2: rt.u8 = _106; rt.byteVecPush(out, rt.btreeAdd(nibbles, { _0: b2 }) ? 1 : 0); rt.byteVecPush(out, rt.hashAdd(seen, { _0: b2 }) ? 1 : 0); } @@ -520,7 +548,13 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } rt.byteVecPush(out, rt.hashLen(seen) & 0xff); const dirs: rt.HashSet = rt.hashNew(rt.hashing(Dir.hash$Hash_DefaultHasher, Dir.eq$PartialEq, true)) as rt.HashSet; - for (const _151 of data) { + const iterS3: Uint8Array = data; + let iterI3: number = 0; + while (true) { + const _151: rt.u8 | rt.Done = iterI3 < iterS3.length ? iterS3[iterI3++] : rt.DONE; + if (_151 === rt.DONE) { + break; + } const _160: rt.usize = rt.usizeRem(_151 as rt.usize, 3); if (!(_160 < 3)) { rt.panic("index out of bounds: the len is " + 3 + " but the index is " + _160); @@ -530,7 +564,13 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, rt.hashLen(dirs) & 0xff); } else { const words: rt.BTreeSet = rt.btreeNew(rt.cmpStr) as rt.BTreeSet; - for (const _175 of data) { + const iterS4: Uint8Array = data; + let iterI4: number = 0; + while (true) { + const _175: rt.u8 | rt.Done = iterI4 < iterS4.length ? iterS4[iterI4++] : rt.DONE; + if (_175 === rt.DONE) { + break; + } const _182: rt.usize = rt.usizeRem(_175 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); if (!(_182 < 8)) { rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _182); @@ -686,7 +726,14 @@ export function btreeMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void if (_197 !== undefined) { _197.n = _197.n ^ 23130; } - for (const b2 of data) { + const iterS: Uint8Array = data; + let iterI: number = 0; + while (true) { + const _205: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_205 === rt.DONE) { + break; + } + const b2: rt.u8 = _205; const r: Rank.Rank = rank(b2, rt.u8Div(b2, 3)); const _212: rt.Entry = rt.entry(ranks, r); if (!rt.entryOccupied(_212)) { @@ -743,7 +790,14 @@ export function btreeMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void } else { const nibbles: rt.BTreeMap = rt.btreeNew(Nibble.cmp$Ord) as rt.BTreeMap; const words: rt.BTreeMap = rt.btreeNew(rt.cmpStr) as rt.BTreeMap; - for (const b3 of data) { + const iterS2: Uint8Array = data; + let iterI2: number = 0; + while (true) { + const _307: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; + if (_307 === rt.DONE) { + break; + } + const b3: rt.u8 = _307; rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeInsert(nibbles, { _0: b3 }, b3), 204)); const _320: rt.usize = rt.usizeRem(b3 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); if (!(_320 < 8)) { @@ -845,7 +899,14 @@ export function deques(data: Uint8Array, out: rt.ByteVec): void { let drained2!: rt.ByteVec; const q: rt.VecDeque = rt.dequeNew() as rt.VecDeque; const pairs: rt.VecDeque<[rt.u8, rt.u8]> = rt.dequeNew() as rt.VecDeque<[rt.u8, rt.u8]>; - for (const b of data) { + const iterS: Uint8Array = data; + let iterI: number = 0; + while (true) { + const _7: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_7 === rt.DONE) { + break; + } + const b: rt.u8 = _7; const _12: rt.u8 = rt.u8Rem(b, 7); if (_12 === 0) { rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequePopFront(q), 238)); @@ -958,7 +1019,13 @@ export function vecs(data: Uint8Array, out: rt.ByteVec): void { pairs.push([b, a as rt.u16] as [rt.u8, rt.u16]); const at = rt.idx(pairs, 0); pairs[at][0] = pairs[at][0] ^ 255; - for (const _39 of pairs) { + const iterS: [rt.u8, rt.u16][] = pairs; + let iterI: number = 0; + while (true) { + const _39: [rt.u8, rt.u16] | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_39 === rt.DONE) { + break; + } rt.byteVecPush(out, _39[0] ^ (_39[1] & 0xff)); } rt.byteVecPush(out, [name, "x", name].length & 0xff); diff --git a/ts/fixtures/lang/expected/fmt.ts b/ts/fixtures/lang/expected/fmt.ts index 9076384ae..ec6d6fb8a 100644 --- a/ts/fixtures/lang/expected/fmt.ts +++ b/ts/fixtures/lang/expected/fmt.ts @@ -129,7 +129,13 @@ export function ints(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { /** Strings padded and escaped, and bytes that may not be UTF-8. */ export function strings(data: Uint8Array, out: rt.ByteVec): void { let flag!: boolean; - for (const _9 of rt.sliceRange(data, 0, rt.min(data.length, 3))) { + const iterS: Uint8Array = rt.sliceRange(data, 0, rt.min(data.length, 3)); + let iterI: number = 0; + while (true) { + const _9: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_9 === rt.DONE) { + break; + } const _15: rt.usize = rt.usizeRem(_9 as rt.usize, ["", "a", "héllo", "日本語", "tab\tnew\nline\r", "quote\"back\\slash'", "\u0000\u0001\u001f", "€Ÿ ­", "é", "‍ᅟ\u2028 ", "͸􏿽", "😀 🇦", "゙゚ン", "{}"].length); if (!(_15 < 14)) { rt.panic("index out of bounds: the len is " + 14 + " but the index is " + _15); diff --git a/ts/fixtures/lang/expected/iters.ts b/ts/fixtures/lang/expected/iters.ts index 8a3258a92..100f38866 100644 --- a/ts/fixtures/lang/expected/iters.ts +++ b/ts/fixtures/lang/expected/iters.ts @@ -22,10 +22,16 @@ export function adaptors(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { }), (b11: rt.u8): boolean => { return rt.u8Rem(b11, 3) !== 0; })))); - for (const _18 of rt.iterToArray(rt.iterFilterMap(rt.iterSlice(data), (_217: rt.u8): rt.u16 | undefined => { + const iterS: rt.u16[] = rt.iterToArray(rt.iterFilterMap(rt.iterSlice(data), (_217: rt.u8): rt.u16 | undefined => { const b12: rt.u8 = _217; return rt.thenSome(b12 < 100, rt.u16Mul(b12 as rt.u16, 200)); - }))) { + })); + let iterI: number = 0; + while (true) { + const _18: rt.u16 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_18 === rt.DONE) { + break; + } rt.byteVecExtendFromSlice(out, rt.u16ToBeBytes(_18)); } } else { @@ -150,7 +156,14 @@ export function adaptors(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { export function chunksByZero$ChunksByZero_u8s(self: Uint8Array): rt.ByteVec[] { const words: rt.ByteVec[] = []; let word: rt.ByteVec = new rt.ByteVec(); - for (const b of self) { + const iterS: Uint8Array = self; + let iterI: number = 0; + while (true) { + const _6: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_6 === rt.DONE) { + break; + } + const b: rt.u8 = _6; if (!(b === 0)) { rt.byteVecPush(word, b); } else { @@ -383,7 +396,13 @@ export function ranges(data: Uint8Array, out: rt.ByteVec): void { return _24; }), 0))); rt.byteVecExtendFromSlice(out, rt.i64ToBeBytes(rt.optionUnwrapOr(rt.iterMin(new rt.Range(rt.i64Sub(rt.i64Neg({ hi: 0x200000, lo: 0 } as rt.i64), 1), rt.i64Add(rt.i64Neg({ hi: 0x200000, lo: 0 } as rt.i64), 1), rt.i64Step)), 0))); - for (const _295 of rt.iterToArray(rt.iterRev(rt.iterStepBy(new rt.Range(0, 48), 8)))) { + const iterS: rt.u32[] = rt.iterToArray(rt.iterRev(rt.iterStepBy(new rt.Range(0, 48), 8))); + let iterI: number = 0; + while (true) { + const _295: rt.u32 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_295 === rt.DONE) { + break; + } rt.byteVecPush(out, _295 & 0xff); } updates(a, b, data, out); diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 8f8e5f137..47047bff6 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -299,9 +299,15 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { bump(copy5.slot); rt.byteVecExtendFromSlice(out, Uint8Array.of(a, copy5.n)); rt.byteVecPush(out, lensBumped(lens)); - for (const _104 of Array.from({ length: 2 }, (): Lens.Lens => { + const iterS: Lens.Lens[] = Array.from({ length: 2 }, (): Lens.Lens => { return copy$Lens(lens); - }).map(copy$Lens)) { + }).map(copy$Lens); + let iterI: number = 0; + while (true) { + const _104: Lens.Lens | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_104 === rt.DONE) { + break; + } bump(_104.slot); } const lenses: Lens.Lens[] = []; @@ -569,7 +575,14 @@ export function reset(m: Moved.Moved): rt.u16 { export function discriminants(data: Uint8Array, out: rt.ByteVec): void { let wide!: Wide.Wide; let signed!: Signed.Signed; - for (const b of data) { + const iterS: Uint8Array = data; + let iterI: number = 0; + while (true) { + const _5: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_5 === rt.DONE) { + break; + } + const b: rt.u8 = _5; const _10: rt.u8 = rt.u8Rem(b, 3); if (_10 === 0) { wide = "Low" as Wide.Wide; @@ -991,7 +1004,14 @@ export function branchLoops(data: Uint8Array, out: rt.ByteVec): void { export function returnedLoop(data: Uint8Array): rt.u8 { let i: rt.usize = 0; while (!(i >= data.length)) { - for (const b of rt.sliceRange(data, i)) { + const iterS: Uint8Array = rt.sliceRange(data, i); + let iterI: number = 0; + while (true) { + const _11: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_11 === rt.DONE) { + break; + } + const b: rt.u8 = _11; if (!(b === 0)) { if (b > 240) { return b ^ (i & 0xff); @@ -1159,7 +1179,13 @@ export function patterns(data: Uint8Array, out: rt.ByteVec): void { } else { rt.byteVecPush(out, 0); } - for (const _33 of rt.sliceRange(data, 0, rt.min(data.length, 4))) { + const iterS: Uint8Array = rt.sliceRange(data, 0, rt.min(data.length, 4)); + let iterI: number = 0; + while (true) { + const _33: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_33 === rt.DONE) { + break; + } b3: { const b: rt.u8 = _33; if (b === 0) { @@ -1259,7 +1285,13 @@ export function closures(data: Uint8Array, out: rt.ByteVec): void { const add: (a0: rt.u8) => void = (v: rt.u8): void => { sum = rt.u32Add(sum, v as rt.u32); }; - for (const _8 of data) { + const iterS: Uint8Array = data; + let iterI: number = 0; + while (true) { + const _8: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_8 === rt.DONE) { + break; + } add(_8); } rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(sum)); @@ -1278,12 +1310,24 @@ export function closures(data: Uint8Array, out: rt.ByteVec): void { overwrite(whole); rt.byteVecPush(out, whole[0]); const parsed: Array = []; - for (const _53 of data) { + const iterS2: Uint8Array = data; + let iterI2: number = 0; + while (true) { + const _53: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; + if (_53 === rt.DONE) { + break; + } const _59: Dir.Dir | undefined = dir(_53); parsed.push(_59); } const tags: rt.ByteVec = new rt.ByteVec(); - for (const _64 of parsed) { + const iterS3: Array = parsed; + let iterI3: number = 0; + while (true) { + const _64: Dir.Dir | undefined | rt.Done = iterI3 < iterS3.length ? iterS3[iterI3++] : rt.DONE; + if (_64 === rt.DONE) { + break; + } const _70: rt.u8 = rt.optionUnwrapOr(rt.optionMap(_64, from$From_Dir_u8), 0); rt.byteVecPush(tags, _70); } @@ -1411,7 +1455,14 @@ export function flows(data: Uint8Array, out: rt.ByteVec): void { let option!: rt.u8 | undefined; let _113!: boolean; let total: rt.u16 = 0; - for (const x of data) { + const iterS: Uint8Array = data; + let iterI: number = 0; + while (true) { + const _7: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_7 === rt.DONE) { + break; + } + const x: rt.u8 = _7; const flow: rt.Result = step(total, x); rt.byteVecExtendFromSlice(out, Uint8Array.of(!flow.ok ? 1 : 0, flow.ok ? 1 : 0)); if (flow.ok) { @@ -1474,7 +1525,14 @@ export function flows(data: Uint8Array, out: rt.ByteVec): void { } } const slot: rt.Mutex = new rt.Mutex(undefined); - for (const x2 of data) { + const iterS2: Uint8Array = data; + let iterI2: number = 0; + while (true) { + const _106: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; + if (_106 === rt.DONE) { + break; + } + const x2: rt.u8 = _106; const held: rt.Mutex = slot; const _114: rt.u8 | undefined = held.value; b12: { diff --git a/ts/fixtures/task/expected/kio.WaiterList.ts b/ts/fixtures/task/expected/kio.WaiterList.ts index 92963af63..b79898064 100644 --- a/ts/fixtures/task/expected/kio.WaiterList.ts +++ b/ts/fixtures/task/expected/kio.WaiterList.ts @@ -16,8 +16,14 @@ function new_(): WaiterList { export function register(self: WaiterList, waiter: Waiter.Waiter): void { const weak: rt.Weak = new rt.Weak(waiter.shared); + const iterS: rt.Weak[] = self.entries; + let iterI: number = 0; b1: { - for (const _8 of self.entries) { + while (true) { + const _8: rt.Weak | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_8 === rt.DONE) { + break; + } if (_8.arc === weak.arc) { break b1; } @@ -36,7 +42,14 @@ export function register(self: WaiterList, waiter: Waiter.Waiter): void { const live: rt.Weak[] = []; const taken = self.entries; self.entries = []; - for (const entry of taken) { + const iterS2: rt.Weak[] = taken; + let iterI2: number = 0; + while (true) { + const _43: rt.Weak | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; + if (_43 === rt.DONE) { + break; + } + const entry: rt.Weak = _43; if (entry.arc.strong > 0) { live.push(entry); } @@ -64,7 +77,13 @@ export function wake(self: WaiterList): void { self.cursor = 0; const taken = self.entries; self.entries = []; - for (const _6 of taken) { + const iterS: rt.Weak[] = taken; + let iterI: number = 0; + while (true) { + const _6: rt.Weak | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_6 === rt.DONE) { + break; + } const _10: rt.Arc | undefined = rt.weakUpgrade(_6); if (_10 !== undefined) { unwind = 15; diff --git a/ts/src/lower/mir/cfg.rs b/ts/src/lower/mir/cfg.rs index 0aa1f195f..06e1a8d5b 100644 --- a/ts/src/lower/mir/cfg.rs +++ b/ts/src/lower/mir/cfg.rs @@ -451,7 +451,7 @@ pub fn simplify(stmts: &mut Vec) { strip_tail(body, &StmtKind::Break(Some(l.clone()))); } } - StmtKind::While { label, body, .. } | StmtKind::ForOf { label, body, .. } => { + StmtKind::While { label, body, .. } => { simplify(body); if let Some(l) = label { strip_tail(body, &StmtKind::Continue(Some(l.clone()))); @@ -480,17 +480,12 @@ pub fn simplify(stmts: &mut Vec) { StmtKind::Block { label: Some(l), body } | StmtKind::While { label: Some(l), body, .. - } - | StmtKind::ForOf { - label: Some(l), body, .. } => !targets(body, l), _ => false, }; if unused { match &mut stmts[i].kind { - StmtKind::Block { label, .. } | StmtKind::While { label, .. } | StmtKind::ForOf { label, .. } => { - *label = None - } + StmtKind::Block { label, .. } | StmtKind::While { label, .. } => *label = None, _ => unreachable!(), } } @@ -540,9 +535,7 @@ pub fn hoist_else(stmts: &mut Vec) { stmts.splice(i + 1..i + 1, els); } } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { - hoist_else(body) - } + StmtKind::Block { body, .. } | StmtKind::While { body, .. } => hoist_else(body), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| hoist_else(body)); hoist_else(default); @@ -573,7 +566,7 @@ fn adopt_labels(stmts: &mut [Stmt]) { for stmt in stmts.iter_mut() { if let StmtKind::Block { label: Some(b), body } = &mut stmt.kind && let [loop_] = body.as_mut_slice() - && let StmtKind::While { label, body, .. } | StmtKind::ForOf { label, body, .. } = &mut loop_.kind + && let StmtKind::While { label, body, .. } = &mut loop_.kind { let l = label.get_or_insert_with(|| b.clone()).clone(); retarget(body, b, &l); @@ -584,9 +577,7 @@ fn adopt_labels(stmts: &mut [Stmt]) { adopt_labels(then); adopt_labels(els); } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { - adopt_labels(body) - } + StmtKind::Block { body, .. } | StmtKind::While { body, .. } => adopt_labels(body), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| adopt_labels(body)); adopt_labels(default); @@ -609,9 +600,7 @@ fn retarget(stmts: &mut [Stmt], from: &str, to: &str) { retarget(then, from, to); retarget(els, from, to); } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { - retarget(body, from, to) - } + StmtKind::Block { body, .. } | StmtKind::While { body, .. } => retarget(body, from, to), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| retarget(body, from, to)); retarget(default, from, to); @@ -651,7 +640,7 @@ fn rotate(stmts: &mut [Stmt]) { rotate(then); rotate(els); } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => rotate(body), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } => rotate(body), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| rotate(body)); rotate(default); @@ -678,9 +667,7 @@ fn unlabel(stmts: &mut [Stmt], innermost: Option<&str>, in_switch: bool) { } StmtKind::Block { body, .. } => unlabel(body, innermost, in_switch), // An unlabeled loop matches no jump's label. - StmtKind::While { label, body, .. } | StmtKind::ForOf { label, body, .. } => { - unlabel(body, Some(label.as_deref().unwrap_or("")), false) - } + StmtKind::While { label, body, .. } => unlabel(body, Some(label.as_deref().unwrap_or("")), false), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| unlabel(body, innermost, true)); unlabel(default, innermost, true); @@ -745,9 +732,7 @@ fn targets(stmts: &[Stmt], label: &str) -> bool { stmts.iter().any(|stmt| match &stmt.kind { StmtKind::Break(Some(l)) | StmtKind::Continue(Some(l)) => l == label, StmtKind::If { then, els, .. } => targets(then, label) || targets(els, label), - StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { - targets(body, label) - } + StmtKind::Block { body, .. } | StmtKind::While { body, .. } => targets(body, label), StmtKind::Catch { body, handler, .. } => targets(body, label) || targets(handler, label), StmtKind::Switch { cases, default, .. } => { cases.iter().any(|(_, body)| targets(body, label)) || targets(default, label) diff --git a/ts/src/lower/mir/inline.rs b/ts/src/lower/mir/inline.rs index 0884c0a4f..2ae487b2e 100644 --- a/ts/src/lower/mir/inline.rs +++ b/ts/src/lower/mir/inline.rs @@ -30,9 +30,7 @@ fn list(stmts: &mut Vec, names: &FxHashMap, shared: &FxHash list(then, names, shared); list(els, names, shared); } - StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { - list(body, names, shared) - } + StmtKind::While { body, .. } | StmtKind::Block { body, .. } => list(body, names, shared), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| list(body, names, shared)); list(default, names, shared); @@ -56,7 +54,7 @@ fn list(stmts: &mut Vec, names: &FxHashMap, shared: &FxHash continue; }; // A literal's type comes from its declaration: an array's may be a tuple's. - let typed = ty.is_some() && matches!(super::step::peel(value), Expr::Array(_) | Expr::Object(_)); + let typed = ty.is_some() && matches!(peel(value), Expr::Array(_) | Expr::Object(_)); if !typed && names.get(name) == Some(&1) && let Some(next) = eager(&stmts[i + 1]) @@ -107,9 +105,7 @@ impl Does { fn eager(stmt: &Stmt) -> Option<&Expr> { match &stmt.kind { StmtKind::Expr(e) | StmtKind::Return(Some(e)) | StmtKind::Throw(e) => Some(e), - StmtKind::Decl { init: Some(e), .. } | StmtKind::If { cond: e, .. } | StmtKind::ForOf { iter: e, .. } => { - Some(e) - } + StmtKind::Decl { init: Some(e), .. } | StmtKind::If { cond: e, .. } => Some(e), StmtKind::Block { body, .. } => body.first().and_then(eager), _ => None, } @@ -118,9 +114,7 @@ fn eager(stmt: &Stmt) -> Option<&Expr> { fn eager_mut(stmt: &mut Stmt) -> Option<&mut Expr> { match &mut stmt.kind { StmtKind::Expr(e) | StmtKind::Return(Some(e)) | StmtKind::Throw(e) => Some(e), - StmtKind::Decl { init: Some(e), .. } | StmtKind::If { cond: e, .. } | StmtKind::ForOf { iter: e, .. } => { - Some(e) - } + StmtKind::Decl { init: Some(e), .. } | StmtKind::If { cond: e, .. } => Some(e), StmtKind::Block { body, .. } => body.first_mut().and_then(eager_mut), _ => None, } @@ -164,3 +158,11 @@ fn expr_assigns(e: &Expr, name: &str) -> bool { }); found } + +/// `e` without its source locations. +fn peel(e: &Expr) -> &Expr { + match e { + Expr::Located(_, e) => peel(e), + e => e, + } +} diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 3ecfa051b..0d986d128 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -1235,8 +1235,6 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { cfg::hoist_else(&mut out); declare_in_place(&mut out); cfg::tidy_loops(&mut out); - // A loop's own labels first, which its header's `break` names. - step::for_of(&mut out); inline::inline_temps(&mut out, &self.shared); // A loop can start by leaving now that what it tests is folded in. cfg::tidy_loops(&mut out); @@ -2399,10 +2397,6 @@ fn scan_stmt(stmt: &Stmt, reads: &mut Vec, lazy: bool) { scan(cond, reads, true); body.iter().for_each(|s| scan_stmt(s, reads, true)); } - StmtKind::ForOf { iter, body, .. } => { - scan(iter, reads, lazy); - body.iter().for_each(|s| scan_stmt(s, reads, true)); - } StmtKind::Block { body, .. } => body.iter().for_each(|s| scan_stmt(s, reads, lazy)), _ => {} } @@ -2582,7 +2576,7 @@ fn scan_reads(stmt: &Stmt, out: &mut Vec) { visit(cond); then.iter().chain(els).for_each(|s| scan_reads(s, out)); } - StmtKind::While { cond: e, body, .. } | StmtKind::ForOf { iter: e, body, .. } => { + StmtKind::While { cond: e, body, .. } => { reads_of(e, out); body.iter().for_each(|s| scan_reads(s, out)); } @@ -2656,9 +2650,7 @@ fn strip_assignments(stmts: &mut Vec, unread: &FxHashSet) { strip_assignments(then, unread); strip_assignments(els, unread); } - StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { - strip_assignments(body, unread) - } + StmtKind::While { body, .. } | StmtKind::Block { body, .. } => strip_assignments(body, unread), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| strip_assignments(body, unread)); strip_assignments(default, unread); @@ -2724,7 +2716,7 @@ fn place_declaration(stmts: &mut [Stmt], name: &str, ty: &Type, total: usize, mu |body: &mut Vec| list_names(body, name) == total && place_declaration(body, name, ty, total, mutable); match &mut stmts[i].kind { StmtKind::If { then, els, .. } => place(then) || place(els), - StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => place(body), + StmtKind::While { body, .. } | StmtKind::Block { body, .. } => place(body), StmtKind::Catch { body, handler, .. } => place(body) || place(handler), StmtKind::Switch { cases, default, .. } => cases.iter_mut().any(|(_, body)| place(body)) || place(default), _ => false, @@ -2771,7 +2763,7 @@ fn visit_stmt(stmt: &Stmt, f: &mut dyn FnMut(&Expr)) { f(cond); then.iter().chain(els).for_each(|s| visit_stmt(s, f)); } - StmtKind::While { cond: e, body, .. } | StmtKind::ForOf { iter: e, body, .. } => { + StmtKind::While { cond: e, body, .. } => { f(e); body.iter().for_each(|s| visit_stmt(s, f)); } @@ -2958,9 +2950,7 @@ fn drop_self_assignments(stmts: &mut Vec) { drop_self_assignments(then); drop_self_assignments(els); } - StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { - drop_self_assignments(body) - } + StmtKind::While { body, .. } | StmtKind::Block { body, .. } => drop_self_assignments(body), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| drop_self_assignments(body)); drop_self_assignments(default); @@ -3000,9 +2990,7 @@ fn return_in_place(stmts: &mut Vec, caught: &FxHashSet) { return_in_place(then, caught); return_in_place(els, caught); } - StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { - return_in_place(body, caught) - } + StmtKind::While { body, .. } | StmtKind::Block { body, .. } => return_in_place(body, caught), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| return_in_place(body, caught)); return_in_place(default, caught); @@ -3079,9 +3067,7 @@ fn handler_reads(stmts: &[Stmt], out: &mut Vec) { handler_reads(then, out); handler_reads(els, out); } - StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { - handler_reads(body, out) - } + StmtKind::While { body, .. } | StmtKind::Block { body, .. } => handler_reads(body, out), StmtKind::Switch { cases, default, .. } => { cases.iter().for_each(|(_, body)| handler_reads(body, out)); handler_reads(default, out); @@ -3145,9 +3131,7 @@ fn breaks_to_return(stmts: &mut [Stmt], label: &str, ret: &Stmt) { breaks_to_return(then, label, ret); breaks_to_return(els, label, ret); } - StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { - breaks_to_return(body, label, ret) - } + StmtKind::While { body, .. } | StmtKind::Block { body, .. } => breaks_to_return(body, label, ret), StmtKind::Switch { cases, default, .. } => { cases .iter_mut() diff --git a/ts/src/lower/mir/step.rs b/ts/src/lower/mir/step.rs index 3b6ef3eeb..82adb926c 100644 --- a/ts/src/lower/mir/step.rs +++ b/ts/src/lower/mir/step.rs @@ -331,194 +331,3 @@ pub(super) fn stepped_field(it: &Expr, key: &str) -> Expr { it => it.clone().member(key), } } - -/// Each loop over an array iterator stepped in place that only the loop steps, as -/// `for (const item of array)`: a `while (true)` whose first statements take the next -/// item and leave on `rt.DONE`. Nothing else names the index, so nothing sees where it -/// stopped. -pub(super) fn for_of(stmts: &mut Vec) { - let mut names: FxHashMap = FxHashMap::default(); - for stmt in stmts.iter() { - super::visit_stmt(stmt, &mut |e| { - super::visit_expr(e, &mut |e| { - if let Expr::Ident(name) = e { - *names.entry(name.clone()).or_default() += 1; - } - }) - }); - } - // The variables declared `= 0`, as an index starts. - let mut zeros = FxHashSet::default(); - decls(stmts, &mut |name, init| { - if matches!(init, Expr::Lit(l) if l == "0") { - zeros.insert(name.to_string()); - } - }); - let mut indexes = FxHashSet::default(); - loops(stmts, &names, &zeros, &mut indexes); - if !indexes.is_empty() { - drop_decls(stmts, &indexes); - } -} - -/// Call `f` on the name and value of each declaration in `stmts` that has one. -fn decls(stmts: &[Stmt], f: &mut dyn FnMut(&str, &Expr)) { - for stmt in stmts { - match &stmt.kind { - StmtKind::Decl { - name, init: Some(init), .. - } => f(name, init), - StmtKind::If { then, els, .. } => { - decls(then, f); - decls(els, f); - } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { - decls(body, f) - } - StmtKind::Switch { cases, default, .. } => { - cases.iter().for_each(|(_, body)| decls(body, f)); - decls(default, f); - } - StmtKind::Catch { body, handler, .. } => { - decls(body, f); - decls(handler, f); - } - _ => {} - } - } -} - -/// Rewrite the loops in `stmts`, collecting the indexes they no longer read. -fn loops( - stmts: &mut [Stmt], - names: &FxHashMap, - zeros: &FxHashSet, - indexes: &mut FxHashSet, -) { - for stmt in stmts.iter_mut() { - // The array and the index are declared, and named only by this loop's header. - if let StmtKind::While { label, cond, body } = &mut stmt.kind - && matches!(cond, Expr::Lit(l) if l == "true") - && let Some((item, array, index)) = header(body, label.as_deref()) - && names.get(&array) == Some(&2) - && names.get(&index) == Some(&2) - && zeros.contains(&index) - { - let mut body: Vec = std::mem::take(body).into_iter().skip(2).collect(); - let mut name = item; - // `const entry = item;` names the item, when nothing else reads it. - if let Some(StmtKind::Decl { - mutable: false, - name: to, - init: Some(Expr::Ident(from)), - .. - }) = body.first().map(|s| &s.kind) - && *from == name - && super::list_names(&body, &name) == 1 - { - name = to.clone(); - body.remove(0); - } - indexes.insert(index); - stmt.kind = StmtKind::ForOf { - label: label.take(), - name, - iter: Expr::ident(array), - body, - }; - } - match &mut stmt.kind { - StmtKind::If { then, els, .. } => { - loops(then, names, zeros, indexes); - loops(els, names, zeros, indexes); - } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { - loops(body, names, zeros, indexes) - } - StmtKind::Switch { cases, default, .. } => { - cases - .iter_mut() - .for_each(|(_, body)| loops(body, names, zeros, indexes)); - loops(default, names, zeros, indexes); - } - StmtKind::Catch { body, handler, .. } => { - loops(body, names, zeros, indexes); - loops(handler, names, zeros, indexes); - } - _ => {} - } - } -} - -/// The item, array, and index of a loop that starts `const item = i < s.length ? -/// s[i++] : rt.DONE; if (item === rt.DONE) break;`, the `break` leaving it. -fn header(body: &[Stmt], label: Option<&str>) -> Option<(String, String, String)> { - let [next, test, ..] = body else { - return None; - }; - let StmtKind::Decl { - mutable: false, - name: item, - init: Some(init), - .. - } = &next.kind - else { - return None; - }; - let Expr::Cond(c, a, b) = peel(init) else { - return None; - }; - let (Expr::Binary(i, "<", len), Expr::Index(s, at), Expr::Rt(done)) = (peel(c), peel(a), peel(b)) else { - return None; - }; - let (Expr::Ident(index), Expr::Member(s2, Key::Name(length)), Expr::Ident(array), Expr::Postfix(i2, "++")) = - (peel(i), peel(len), peel(s), peel(at)) - else { - return None; - }; - let same = |e: &Expr, name: &str| matches!(peel(e), Expr::Ident(n) if n == name); - if done != "DONE" || length != "length" || !same(s2, array) || !same(i2, index) { - return None; - } - let StmtKind::If { cond, then, els } = &test.kind else { - return None; - }; - let leaves = matches!(then.as_slice(), [Stmt { kind: StmtKind::Break(target), .. }] - if target.is_none() || target.as_deref() == label); - let tests = matches!(peel(cond), Expr::Binary(l, "===", r) - if same(l, item) && matches!(peel(r), Expr::Rt(d) if d == "DONE")); - (leaves && tests && els.is_empty()).then(|| (item.clone(), array.clone(), index.clone())) -} - -/// `e` without its source location. -pub(super) fn peel(e: &Expr) -> &Expr { - match e { - Expr::Located(_, e) => peel(e), - e => e, - } -} - -/// Drop the declarations of `names`, which nothing reads any more. -fn drop_decls(stmts: &mut Vec, names: &FxHashSet) { - stmts.retain(|s| !matches!(&s.kind, StmtKind::Decl { name, .. } if names.contains(name))); - for stmt in stmts.iter_mut() { - match &mut stmt.kind { - StmtKind::If { then, els, .. } => { - drop_decls(then, names); - drop_decls(els, names); - } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { - drop_decls(body, names) - } - StmtKind::Switch { cases, default, .. } => { - cases.iter_mut().for_each(|(_, body)| drop_decls(body, names)); - drop_decls(default, names); - } - StmtKind::Catch { body, handler, .. } => { - drop_decls(body, names); - drop_decls(handler, names); - } - _ => {} - } - } -} diff --git a/ts/src/print.rs b/ts/src/print.rs index cda3e9204..1d05f2eac 100644 --- a/ts/src/print.rs +++ b/ts/src/print.rs @@ -313,8 +313,8 @@ impl Refs { self.stmts(program, then); self.stmts(program, els); } - StmtKind::While { cond: e, body, .. } | StmtKind::ForOf { iter: e, body, .. } => { - self.expr(program, e); + StmtKind::While { cond, body, .. } => { + self.expr(program, cond); self.stmts(program, body); } StmtKind::Block { body, .. } => self.stmts(program, body), @@ -746,21 +746,6 @@ impl Printer<'_> { self.start(); self.write("}\n"); } - StmtKind::ForOf { - label, - name, - iter, - body, - } => { - self.label(label); - let name = self.local(name).to_string(); - self.write(&format!("for (const {name} of ")); - self.expr(iter, 2); - self.write(") {\n"); - self.block_body(body); - self.start(); - self.write("}\n"); - } StmtKind::Block { label, body } => { self.label(label); self.write("{\n"); @@ -1170,11 +1155,6 @@ fn collect_locals(stmts: &[Stmt], out: &mut Vec) { collect_expr_locals(cond, out); collect_locals(body, out); } - StmtKind::ForOf { name, iter, body, .. } => { - out.push(name.clone()); - collect_expr_locals(iter, out); - collect_locals(body, out); - } StmtKind::Block { body, .. } => collect_locals(body, out), StmtKind::Catch { body, name, handler } => { collect_locals(body, out); diff --git a/ts/src/ts.rs b/ts/src/ts.rs index f95469f25..d88ba77a1 100644 --- a/ts/src/ts.rs +++ b/ts/src/ts.rs @@ -200,13 +200,6 @@ pub enum StmtKind { cond: Expr, body: Vec, }, - /// `for (const name of iter) body`, over an array. - ForOf { - label: Option, - name: String, - iter: Expr, - body: Vec, - }, Block { label: Option, body: Vec, @@ -287,7 +280,7 @@ fn breaks_out(stmts: &[Stmt], label: Option<&str>, nested: bool) -> bool { StmtKind::Switch { cases, default, .. } => { cases.iter().any(|(_, body)| breaks_out(body, label, true)) || breaks_out(default, label, true) } - StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => breaks_out(body, label, true), + StmtKind::While { body, .. } => breaks_out(body, label, true), _ => false, }) } From 9b9ae612edd11f542fa5db25ebff6046554f9801 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:31:15 -0700 Subject: [PATCH 07/15] Revert "fix(ts): keep stepped loops as while loops" The Firefox gap was the bench's first translated route, not for-of: timed the other way round, the stepped loops were the slow ones by the same margin, and each A/A copy matched the other build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- .../codec/expected/coding/version.Versions.ts | 16 +- ts/fixtures/codec/expected/harness.ts | 17 +- ts/fixtures/lang/expected/chars.ts | 25 +-- ts/fixtures/lang/expected/collections.ts | 87 +------- ts/fixtures/lang/expected/fmt.ts | 8 +- ts/fixtures/lang/expected/iters.ts | 27 +-- ts/fixtures/lang/expected/shapes.ts | 78 +------ ts/fixtures/task/expected/kio.WaiterList.ts | 25 +-- ts/src/lower/mir/cfg.rs | 33 ++- ts/src/lower/mir/inline.rs | 22 +- ts/src/lower/mir/mod.rs | 32 ++- ts/src/lower/mir/step.rs | 191 ++++++++++++++++++ ts/src/print.rs | 24 ++- ts/src/ts.rs | 9 +- 14 files changed, 314 insertions(+), 280 deletions(-) diff --git a/ts/fixtures/codec/expected/coding/version.Versions.ts b/ts/fixtures/codec/expected/coding/version.Versions.ts index 35e75ebad..f1a961f65 100644 --- a/ts/fixtures/codec/expected/coding/version.Versions.ts +++ b/ts/fixtures/codec/expected/coding/version.Versions.ts @@ -49,13 +49,7 @@ export function decode$Decode_Form(r: Decoder.Decoder, version: Form.Form): rt.R export function encode$Encode_Form(self: Versions, w: Encoder.Encoder, version: Form.Form): rt.Result { const _4: rt.Result = Encoder.varint(w, self._0.length as rt.u64); if (_4.ok) { - const iterS: Version.Version[] = self._0; - let iterI: number = 0; - while (true) { - const _14: Version.Version | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_14 === rt.DONE) { - break; - } + for (const _14 of self._0) { const _18: rt.Result = Version.encode$Encode_Form(_14, w, version); if (!_18.ok) { return _18; @@ -70,13 +64,7 @@ export function encode$Encode_Form(self: Versions, w: Encoder.Encoder, version: export function encode$Encode_Version(self: Versions, w: Encoder.Encoder, version: version_Version.Version): rt.Result { const _4: rt.Result = Encoder.varint(w, self._0.length as rt.u64); if (_4.ok) { - const iterS: Version.Version[] = self._0; - let iterI: number = 0; - while (true) { - const _14: Version.Version | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_14 === rt.DONE) { - break; - } + for (const _14 of self._0) { const _18: rt.Result = Version.encode$Encode_Version(_14, w, version); if (!_18.ok) { return _18; diff --git a/ts/fixtures/codec/expected/harness.ts b/ts/fixtures/codec/expected/harness.ts index 1a3cc0f3d..1efea3b26 100644 --- a/ts/fixtures/codec/expected/harness.ts +++ b/ts/fixtures/codec/expected/harness.ts @@ -200,13 +200,7 @@ export function decodeScript(data: Uint8Array, out: rt.ByteVec): void { if (_9 !== undefined) { const _13: [Uint8Array, Uint8Array] = rt.sliceSplitAt(_9[1], rt.min(_9[1].length, _9[0] as rt.usize)); const r: Decoder.Decoder = Decoder.new(_13[1], form(selector)); - const iterS: Uint8Array = _13[0]; - let iterI: number = 0; - while (true) { - const _21: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_21 === rt.DONE) { - break; - } + for (const _21 of _13[0]) { const _26: rt.Result = decodeStep(r, _21, out); if (_26.ok) { rt.byteVecPush(out, 0); @@ -324,14 +318,7 @@ export function encodeScript(data: Uint8Array, out: rt.ByteVec): void { const _20: Form.Form = form(selector); const w: Encoder.Encoder = Encoder.new(buf, _20); const prefixes: Prefix.Prefix[] = []; - const iterS: Uint8Array = _13[0]; - let iterI: number = 0; - while (true) { - const _24: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_24 === rt.DONE) { - break; - } - const step: rt.u8 = _24; + for (const step of _13[0]) { const _30: [rt.u64, Uint8Array] = takeU64(values); const value: rt.u64 = _30[0]; values = _30[1]; diff --git a/ts/fixtures/lang/expected/chars.ts b/ts/fixtures/lang/expected/chars.ts index 93828aeca..d569e3a00 100644 --- a/ts/fixtures/lang/expected/chars.ts +++ b/ts/fixtures/lang/expected/chars.ts @@ -67,13 +67,7 @@ export function class_(c: rt.char): rt.u8 { export function chars(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _4: rt.u8 = rt.u8Rem(kind, 4); if (_4 === 0) { - const iterS: rt.u32[] = scalars(data); - let iterI: number = 0; - while (true) { - const _10: rt.u32 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_10 === rt.DONE) { - break; - } + for (const _10 of scalars(data)) { const _14: rt.char | undefined = rt.charFromU32(_10); if (_14 === undefined) { rt.byteVecPush(out, 255); @@ -84,14 +78,7 @@ export function chars(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } } } else if (_4 === 1) { - const iterS2: rt.u32[] = scalars(data); - let iterI2: number = 0; - while (true) { - const _27: rt.u32 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_27 === rt.DONE) { - break; - } - const n2: rt.u32 = _27; + for (const n2 of scalars(data)) { const c2: rt.char = rt.optionUnwrapOr(rt.charFromU32(n2), (n2 & 0xff) as rt.char); rt.byteVecPush(out, c2 & 0xff); rt.byteVecExtendFromSlice(out, rt.u16ToBeBytes(c2 & 0xffff)); @@ -131,13 +118,7 @@ export function chars(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(_128 as rt.u32)); } } else { - const iterS3: rt.u32[] = scalars(data); - let iterI3: number = 0; - while (true) { - const _140: rt.u32 | rt.Done = iterI3 < iterS3.length ? iterS3[iterI3++] : rt.DONE; - if (_140 === rt.DONE) { - break; - } + for (const _140 of scalars(data)) { const _144: rt.char | undefined = rt.charFromU32(_140); if (_144 !== undefined) { const arg = ([_144] as [rt.char])[0]; diff --git a/ts/fixtures/lang/expected/collections.ts b/ts/fixtures/lang/expected/collections.ts index 361f58975..0d9b2a13d 100644 --- a/ts/fixtures/lang/expected/collections.ts +++ b/ts/fixtures/lang/expected/collections.ts @@ -285,14 +285,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { return t14.n & 0xff; })); } - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _380: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_380 === rt.DONE) { - break; - } - const b5: rt.u8 = _380; + for (const b5 of data) { rt.byteVecPush(out, claim(copy2, rt.u8Rem(b5, 8), b5 as rt.u16)); } const stamped: rt.HashMap = rt.hashNew() as rt.HashMap; @@ -351,14 +344,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, rt.hashLen(tuples) & 0xff); } else { const words: rt.HashMap = rt.hashNew() as rt.HashMap; - const iterS2: Uint8Array = data; - let iterI2: number = 0; - while (true) { - const _496: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_496 === rt.DONE) { - break; - } - const b6: rt.u8 = _496; + for (const b6 of data) { const _502: rt.usize = rt.usizeRem(b6 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); if (!(_502 < 8)) { rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _502); @@ -465,14 +451,7 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { if (_4 === 0) { const hashed: rt.HashSet = rt.hashNew() as rt.HashSet; const sorted: rt.BTreeSet = rt.btreeNew(rt.cmp) as rt.BTreeSet; - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _10: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_10 === rt.DONE) { - break; - } - const b: rt.u8 = _10; + for (const b of data) { const v: rt.u16 = rt.u16Rem(b as rt.u16, 24); const _17: rt.u8 = rt.u8Rem(b, 3); if (_17 === 0) { @@ -514,14 +493,7 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } else if (_4 === 1) { const nibbles: rt.BTreeSet = rt.btreeNew(Nibble.cmp$Ord) as rt.BTreeSet; const seen: rt.HashSet = rt.hashNew(rt.hashing(Nibble.hash$Hash_DefaultHasher, Nibble.eq$PartialEq)) as rt.HashSet; - const iterS2: Uint8Array = data; - let iterI2: number = 0; - while (true) { - const _106: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_106 === rt.DONE) { - break; - } - const b2: rt.u8 = _106; + for (const b2 of data) { rt.byteVecPush(out, rt.btreeAdd(nibbles, { _0: b2 }) ? 1 : 0); rt.byteVecPush(out, rt.hashAdd(seen, { _0: b2 }) ? 1 : 0); } @@ -548,13 +520,7 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } rt.byteVecPush(out, rt.hashLen(seen) & 0xff); const dirs: rt.HashSet = rt.hashNew(rt.hashing(Dir.hash$Hash_DefaultHasher, Dir.eq$PartialEq, true)) as rt.HashSet; - const iterS3: Uint8Array = data; - let iterI3: number = 0; - while (true) { - const _151: rt.u8 | rt.Done = iterI3 < iterS3.length ? iterS3[iterI3++] : rt.DONE; - if (_151 === rt.DONE) { - break; - } + for (const _151 of data) { const _160: rt.usize = rt.usizeRem(_151 as rt.usize, 3); if (!(_160 < 3)) { rt.panic("index out of bounds: the len is " + 3 + " but the index is " + _160); @@ -564,13 +530,7 @@ export function sets(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, rt.hashLen(dirs) & 0xff); } else { const words: rt.BTreeSet = rt.btreeNew(rt.cmpStr) as rt.BTreeSet; - const iterS4: Uint8Array = data; - let iterI4: number = 0; - while (true) { - const _175: rt.u8 | rt.Done = iterI4 < iterS4.length ? iterS4[iterI4++] : rt.DONE; - if (_175 === rt.DONE) { - break; - } + for (const _175 of data) { const _182: rt.usize = rt.usizeRem(_175 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); if (!(_182 < 8)) { rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _182); @@ -726,14 +686,7 @@ export function btreeMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void if (_197 !== undefined) { _197.n = _197.n ^ 23130; } - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _205: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_205 === rt.DONE) { - break; - } - const b2: rt.u8 = _205; + for (const b2 of data) { const r: Rank.Rank = rank(b2, rt.u8Div(b2, 3)); const _212: rt.Entry = rt.entry(ranks, r); if (!rt.entryOccupied(_212)) { @@ -790,14 +743,7 @@ export function btreeMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void } else { const nibbles: rt.BTreeMap = rt.btreeNew(Nibble.cmp$Ord) as rt.BTreeMap; const words: rt.BTreeMap = rt.btreeNew(rt.cmpStr) as rt.BTreeMap; - const iterS2: Uint8Array = data; - let iterI2: number = 0; - while (true) { - const _307: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_307 === rt.DONE) { - break; - } - const b3: rt.u8 = _307; + for (const b3 of data) { rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeInsert(nibbles, { _0: b3 }, b3), 204)); const _320: rt.usize = rt.usizeRem(b3 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); if (!(_320 < 8)) { @@ -899,14 +845,7 @@ export function deques(data: Uint8Array, out: rt.ByteVec): void { let drained2!: rt.ByteVec; const q: rt.VecDeque = rt.dequeNew() as rt.VecDeque; const pairs: rt.VecDeque<[rt.u8, rt.u8]> = rt.dequeNew() as rt.VecDeque<[rt.u8, rt.u8]>; - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _7: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_7 === rt.DONE) { - break; - } - const b: rt.u8 = _7; + for (const b of data) { const _12: rt.u8 = rt.u8Rem(b, 7); if (_12 === 0) { rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequePopFront(q), 238)); @@ -1019,13 +958,7 @@ export function vecs(data: Uint8Array, out: rt.ByteVec): void { pairs.push([b, a as rt.u16] as [rt.u8, rt.u16]); const at = rt.idx(pairs, 0); pairs[at][0] = pairs[at][0] ^ 255; - const iterS: [rt.u8, rt.u16][] = pairs; - let iterI: number = 0; - while (true) { - const _39: [rt.u8, rt.u16] | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_39 === rt.DONE) { - break; - } + for (const _39 of pairs) { rt.byteVecPush(out, _39[0] ^ (_39[1] & 0xff)); } rt.byteVecPush(out, [name, "x", name].length & 0xff); diff --git a/ts/fixtures/lang/expected/fmt.ts b/ts/fixtures/lang/expected/fmt.ts index ec6d6fb8a..9076384ae 100644 --- a/ts/fixtures/lang/expected/fmt.ts +++ b/ts/fixtures/lang/expected/fmt.ts @@ -129,13 +129,7 @@ export function ints(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { /** Strings padded and escaped, and bytes that may not be UTF-8. */ export function strings(data: Uint8Array, out: rt.ByteVec): void { let flag!: boolean; - const iterS: Uint8Array = rt.sliceRange(data, 0, rt.min(data.length, 3)); - let iterI: number = 0; - while (true) { - const _9: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_9 === rt.DONE) { - break; - } + for (const _9 of rt.sliceRange(data, 0, rt.min(data.length, 3))) { const _15: rt.usize = rt.usizeRem(_9 as rt.usize, ["", "a", "héllo", "日本語", "tab\tnew\nline\r", "quote\"back\\slash'", "\u0000\u0001\u001f", "€Ÿ ­", "é", "‍ᅟ\u2028 ", "͸􏿽", "😀 🇦", "゙゚ン", "{}"].length); if (!(_15 < 14)) { rt.panic("index out of bounds: the len is " + 14 + " but the index is " + _15); diff --git a/ts/fixtures/lang/expected/iters.ts b/ts/fixtures/lang/expected/iters.ts index 100f38866..8a3258a92 100644 --- a/ts/fixtures/lang/expected/iters.ts +++ b/ts/fixtures/lang/expected/iters.ts @@ -22,16 +22,10 @@ export function adaptors(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { }), (b11: rt.u8): boolean => { return rt.u8Rem(b11, 3) !== 0; })))); - const iterS: rt.u16[] = rt.iterToArray(rt.iterFilterMap(rt.iterSlice(data), (_217: rt.u8): rt.u16 | undefined => { + for (const _18 of rt.iterToArray(rt.iterFilterMap(rt.iterSlice(data), (_217: rt.u8): rt.u16 | undefined => { const b12: rt.u8 = _217; return rt.thenSome(b12 < 100, rt.u16Mul(b12 as rt.u16, 200)); - })); - let iterI: number = 0; - while (true) { - const _18: rt.u16 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_18 === rt.DONE) { - break; - } + }))) { rt.byteVecExtendFromSlice(out, rt.u16ToBeBytes(_18)); } } else { @@ -156,14 +150,7 @@ export function adaptors(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { export function chunksByZero$ChunksByZero_u8s(self: Uint8Array): rt.ByteVec[] { const words: rt.ByteVec[] = []; let word: rt.ByteVec = new rt.ByteVec(); - const iterS: Uint8Array = self; - let iterI: number = 0; - while (true) { - const _6: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_6 === rt.DONE) { - break; - } - const b: rt.u8 = _6; + for (const b of self) { if (!(b === 0)) { rt.byteVecPush(word, b); } else { @@ -396,13 +383,7 @@ export function ranges(data: Uint8Array, out: rt.ByteVec): void { return _24; }), 0))); rt.byteVecExtendFromSlice(out, rt.i64ToBeBytes(rt.optionUnwrapOr(rt.iterMin(new rt.Range(rt.i64Sub(rt.i64Neg({ hi: 0x200000, lo: 0 } as rt.i64), 1), rt.i64Add(rt.i64Neg({ hi: 0x200000, lo: 0 } as rt.i64), 1), rt.i64Step)), 0))); - const iterS: rt.u32[] = rt.iterToArray(rt.iterRev(rt.iterStepBy(new rt.Range(0, 48), 8))); - let iterI: number = 0; - while (true) { - const _295: rt.u32 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_295 === rt.DONE) { - break; - } + for (const _295 of rt.iterToArray(rt.iterRev(rt.iterStepBy(new rt.Range(0, 48), 8)))) { rt.byteVecPush(out, _295 & 0xff); } updates(a, b, data, out); diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 47047bff6..8f8e5f137 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -299,15 +299,9 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { bump(copy5.slot); rt.byteVecExtendFromSlice(out, Uint8Array.of(a, copy5.n)); rt.byteVecPush(out, lensBumped(lens)); - const iterS: Lens.Lens[] = Array.from({ length: 2 }, (): Lens.Lens => { + for (const _104 of Array.from({ length: 2 }, (): Lens.Lens => { return copy$Lens(lens); - }).map(copy$Lens); - let iterI: number = 0; - while (true) { - const _104: Lens.Lens | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_104 === rt.DONE) { - break; - } + }).map(copy$Lens)) { bump(_104.slot); } const lenses: Lens.Lens[] = []; @@ -575,14 +569,7 @@ export function reset(m: Moved.Moved): rt.u16 { export function discriminants(data: Uint8Array, out: rt.ByteVec): void { let wide!: Wide.Wide; let signed!: Signed.Signed; - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _5: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_5 === rt.DONE) { - break; - } - const b: rt.u8 = _5; + for (const b of data) { const _10: rt.u8 = rt.u8Rem(b, 3); if (_10 === 0) { wide = "Low" as Wide.Wide; @@ -1004,14 +991,7 @@ export function branchLoops(data: Uint8Array, out: rt.ByteVec): void { export function returnedLoop(data: Uint8Array): rt.u8 { let i: rt.usize = 0; while (!(i >= data.length)) { - const iterS: Uint8Array = rt.sliceRange(data, i); - let iterI: number = 0; - while (true) { - const _11: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_11 === rt.DONE) { - break; - } - const b: rt.u8 = _11; + for (const b of rt.sliceRange(data, i)) { if (!(b === 0)) { if (b > 240) { return b ^ (i & 0xff); @@ -1179,13 +1159,7 @@ export function patterns(data: Uint8Array, out: rt.ByteVec): void { } else { rt.byteVecPush(out, 0); } - const iterS: Uint8Array = rt.sliceRange(data, 0, rt.min(data.length, 4)); - let iterI: number = 0; - while (true) { - const _33: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_33 === rt.DONE) { - break; - } + for (const _33 of rt.sliceRange(data, 0, rt.min(data.length, 4))) { b3: { const b: rt.u8 = _33; if (b === 0) { @@ -1285,13 +1259,7 @@ export function closures(data: Uint8Array, out: rt.ByteVec): void { const add: (a0: rt.u8) => void = (v: rt.u8): void => { sum = rt.u32Add(sum, v as rt.u32); }; - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _8: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_8 === rt.DONE) { - break; - } + for (const _8 of data) { add(_8); } rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(sum)); @@ -1310,24 +1278,12 @@ export function closures(data: Uint8Array, out: rt.ByteVec): void { overwrite(whole); rt.byteVecPush(out, whole[0]); const parsed: Array = []; - const iterS2: Uint8Array = data; - let iterI2: number = 0; - while (true) { - const _53: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_53 === rt.DONE) { - break; - } + for (const _53 of data) { const _59: Dir.Dir | undefined = dir(_53); parsed.push(_59); } const tags: rt.ByteVec = new rt.ByteVec(); - const iterS3: Array = parsed; - let iterI3: number = 0; - while (true) { - const _64: Dir.Dir | undefined | rt.Done = iterI3 < iterS3.length ? iterS3[iterI3++] : rt.DONE; - if (_64 === rt.DONE) { - break; - } + for (const _64 of parsed) { const _70: rt.u8 = rt.optionUnwrapOr(rt.optionMap(_64, from$From_Dir_u8), 0); rt.byteVecPush(tags, _70); } @@ -1455,14 +1411,7 @@ export function flows(data: Uint8Array, out: rt.ByteVec): void { let option!: rt.u8 | undefined; let _113!: boolean; let total: rt.u16 = 0; - const iterS: Uint8Array = data; - let iterI: number = 0; - while (true) { - const _7: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_7 === rt.DONE) { - break; - } - const x: rt.u8 = _7; + for (const x of data) { const flow: rt.Result = step(total, x); rt.byteVecExtendFromSlice(out, Uint8Array.of(!flow.ok ? 1 : 0, flow.ok ? 1 : 0)); if (flow.ok) { @@ -1525,14 +1474,7 @@ export function flows(data: Uint8Array, out: rt.ByteVec): void { } } const slot: rt.Mutex = new rt.Mutex(undefined); - const iterS2: Uint8Array = data; - let iterI2: number = 0; - while (true) { - const _106: rt.u8 | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_106 === rt.DONE) { - break; - } - const x2: rt.u8 = _106; + for (const x2 of data) { const held: rt.Mutex = slot; const _114: rt.u8 | undefined = held.value; b12: { diff --git a/ts/fixtures/task/expected/kio.WaiterList.ts b/ts/fixtures/task/expected/kio.WaiterList.ts index b79898064..92963af63 100644 --- a/ts/fixtures/task/expected/kio.WaiterList.ts +++ b/ts/fixtures/task/expected/kio.WaiterList.ts @@ -16,14 +16,8 @@ function new_(): WaiterList { export function register(self: WaiterList, waiter: Waiter.Waiter): void { const weak: rt.Weak = new rt.Weak(waiter.shared); - const iterS: rt.Weak[] = self.entries; - let iterI: number = 0; b1: { - while (true) { - const _8: rt.Weak | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_8 === rt.DONE) { - break; - } + for (const _8 of self.entries) { if (_8.arc === weak.arc) { break b1; } @@ -42,14 +36,7 @@ export function register(self: WaiterList, waiter: Waiter.Waiter): void { const live: rt.Weak[] = []; const taken = self.entries; self.entries = []; - const iterS2: rt.Weak[] = taken; - let iterI2: number = 0; - while (true) { - const _43: rt.Weak | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_43 === rt.DONE) { - break; - } - const entry: rt.Weak = _43; + for (const entry of taken) { if (entry.arc.strong > 0) { live.push(entry); } @@ -77,13 +64,7 @@ export function wake(self: WaiterList): void { self.cursor = 0; const taken = self.entries; self.entries = []; - const iterS: rt.Weak[] = taken; - let iterI: number = 0; - while (true) { - const _6: rt.Weak | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_6 === rt.DONE) { - break; - } + for (const _6 of taken) { const _10: rt.Arc | undefined = rt.weakUpgrade(_6); if (_10 !== undefined) { unwind = 15; diff --git a/ts/src/lower/mir/cfg.rs b/ts/src/lower/mir/cfg.rs index 06e1a8d5b..0aa1f195f 100644 --- a/ts/src/lower/mir/cfg.rs +++ b/ts/src/lower/mir/cfg.rs @@ -451,7 +451,7 @@ pub fn simplify(stmts: &mut Vec) { strip_tail(body, &StmtKind::Break(Some(l.clone()))); } } - StmtKind::While { label, body, .. } => { + StmtKind::While { label, body, .. } | StmtKind::ForOf { label, body, .. } => { simplify(body); if let Some(l) = label { strip_tail(body, &StmtKind::Continue(Some(l.clone()))); @@ -480,12 +480,17 @@ pub fn simplify(stmts: &mut Vec) { StmtKind::Block { label: Some(l), body } | StmtKind::While { label: Some(l), body, .. + } + | StmtKind::ForOf { + label: Some(l), body, .. } => !targets(body, l), _ => false, }; if unused { match &mut stmts[i].kind { - StmtKind::Block { label, .. } | StmtKind::While { label, .. } => *label = None, + StmtKind::Block { label, .. } | StmtKind::While { label, .. } | StmtKind::ForOf { label, .. } => { + *label = None + } _ => unreachable!(), } } @@ -535,7 +540,9 @@ pub fn hoist_else(stmts: &mut Vec) { stmts.splice(i + 1..i + 1, els); } } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } => hoist_else(body), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + hoist_else(body) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| hoist_else(body)); hoist_else(default); @@ -566,7 +573,7 @@ fn adopt_labels(stmts: &mut [Stmt]) { for stmt in stmts.iter_mut() { if let StmtKind::Block { label: Some(b), body } = &mut stmt.kind && let [loop_] = body.as_mut_slice() - && let StmtKind::While { label, body, .. } = &mut loop_.kind + && let StmtKind::While { label, body, .. } | StmtKind::ForOf { label, body, .. } = &mut loop_.kind { let l = label.get_or_insert_with(|| b.clone()).clone(); retarget(body, b, &l); @@ -577,7 +584,9 @@ fn adopt_labels(stmts: &mut [Stmt]) { adopt_labels(then); adopt_labels(els); } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } => adopt_labels(body), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + adopt_labels(body) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| adopt_labels(body)); adopt_labels(default); @@ -600,7 +609,9 @@ fn retarget(stmts: &mut [Stmt], from: &str, to: &str) { retarget(then, from, to); retarget(els, from, to); } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } => retarget(body, from, to), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + retarget(body, from, to) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| retarget(body, from, to)); retarget(default, from, to); @@ -640,7 +651,7 @@ fn rotate(stmts: &mut [Stmt]) { rotate(then); rotate(els); } - StmtKind::Block { body, .. } | StmtKind::While { body, .. } => rotate(body), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => rotate(body), StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| rotate(body)); rotate(default); @@ -667,7 +678,9 @@ fn unlabel(stmts: &mut [Stmt], innermost: Option<&str>, in_switch: bool) { } StmtKind::Block { body, .. } => unlabel(body, innermost, in_switch), // An unlabeled loop matches no jump's label. - StmtKind::While { label, body, .. } => unlabel(body, Some(label.as_deref().unwrap_or("")), false), + StmtKind::While { label, body, .. } | StmtKind::ForOf { label, body, .. } => { + unlabel(body, Some(label.as_deref().unwrap_or("")), false) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| unlabel(body, innermost, true)); unlabel(default, innermost, true); @@ -732,7 +745,9 @@ fn targets(stmts: &[Stmt], label: &str) -> bool { stmts.iter().any(|stmt| match &stmt.kind { StmtKind::Break(Some(l)) | StmtKind::Continue(Some(l)) => l == label, StmtKind::If { then, els, .. } => targets(then, label) || targets(els, label), - StmtKind::Block { body, .. } | StmtKind::While { body, .. } => targets(body, label), + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + targets(body, label) + } StmtKind::Catch { body, handler, .. } => targets(body, label) || targets(handler, label), StmtKind::Switch { cases, default, .. } => { cases.iter().any(|(_, body)| targets(body, label)) || targets(default, label) diff --git a/ts/src/lower/mir/inline.rs b/ts/src/lower/mir/inline.rs index 2ae487b2e..0884c0a4f 100644 --- a/ts/src/lower/mir/inline.rs +++ b/ts/src/lower/mir/inline.rs @@ -30,7 +30,9 @@ fn list(stmts: &mut Vec, names: &FxHashMap, shared: &FxHash list(then, names, shared); list(els, names, shared); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => list(body, names, shared), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + list(body, names, shared) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| list(body, names, shared)); list(default, names, shared); @@ -54,7 +56,7 @@ fn list(stmts: &mut Vec, names: &FxHashMap, shared: &FxHash continue; }; // A literal's type comes from its declaration: an array's may be a tuple's. - let typed = ty.is_some() && matches!(peel(value), Expr::Array(_) | Expr::Object(_)); + let typed = ty.is_some() && matches!(super::step::peel(value), Expr::Array(_) | Expr::Object(_)); if !typed && names.get(name) == Some(&1) && let Some(next) = eager(&stmts[i + 1]) @@ -105,7 +107,9 @@ impl Does { fn eager(stmt: &Stmt) -> Option<&Expr> { match &stmt.kind { StmtKind::Expr(e) | StmtKind::Return(Some(e)) | StmtKind::Throw(e) => Some(e), - StmtKind::Decl { init: Some(e), .. } | StmtKind::If { cond: e, .. } => Some(e), + StmtKind::Decl { init: Some(e), .. } | StmtKind::If { cond: e, .. } | StmtKind::ForOf { iter: e, .. } => { + Some(e) + } StmtKind::Block { body, .. } => body.first().and_then(eager), _ => None, } @@ -114,7 +118,9 @@ fn eager(stmt: &Stmt) -> Option<&Expr> { fn eager_mut(stmt: &mut Stmt) -> Option<&mut Expr> { match &mut stmt.kind { StmtKind::Expr(e) | StmtKind::Return(Some(e)) | StmtKind::Throw(e) => Some(e), - StmtKind::Decl { init: Some(e), .. } | StmtKind::If { cond: e, .. } => Some(e), + StmtKind::Decl { init: Some(e), .. } | StmtKind::If { cond: e, .. } | StmtKind::ForOf { iter: e, .. } => { + Some(e) + } StmtKind::Block { body, .. } => body.first_mut().and_then(eager_mut), _ => None, } @@ -158,11 +164,3 @@ fn expr_assigns(e: &Expr, name: &str) -> bool { }); found } - -/// `e` without its source locations. -fn peel(e: &Expr) -> &Expr { - match e { - Expr::Located(_, e) => peel(e), - e => e, - } -} diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 0d986d128..3ecfa051b 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -1235,6 +1235,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { cfg::hoist_else(&mut out); declare_in_place(&mut out); cfg::tidy_loops(&mut out); + // A loop's own labels first, which its header's `break` names. + step::for_of(&mut out); inline::inline_temps(&mut out, &self.shared); // A loop can start by leaving now that what it tests is folded in. cfg::tidy_loops(&mut out); @@ -2397,6 +2399,10 @@ fn scan_stmt(stmt: &Stmt, reads: &mut Vec, lazy: bool) { scan(cond, reads, true); body.iter().for_each(|s| scan_stmt(s, reads, true)); } + StmtKind::ForOf { iter, body, .. } => { + scan(iter, reads, lazy); + body.iter().for_each(|s| scan_stmt(s, reads, true)); + } StmtKind::Block { body, .. } => body.iter().for_each(|s| scan_stmt(s, reads, lazy)), _ => {} } @@ -2576,7 +2582,7 @@ fn scan_reads(stmt: &Stmt, out: &mut Vec) { visit(cond); then.iter().chain(els).for_each(|s| scan_reads(s, out)); } - StmtKind::While { cond: e, body, .. } => { + StmtKind::While { cond: e, body, .. } | StmtKind::ForOf { iter: e, body, .. } => { reads_of(e, out); body.iter().for_each(|s| scan_reads(s, out)); } @@ -2650,7 +2656,9 @@ fn strip_assignments(stmts: &mut Vec, unread: &FxHashSet) { strip_assignments(then, unread); strip_assignments(els, unread); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => strip_assignments(body, unread), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + strip_assignments(body, unread) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| strip_assignments(body, unread)); strip_assignments(default, unread); @@ -2716,7 +2724,7 @@ fn place_declaration(stmts: &mut [Stmt], name: &str, ty: &Type, total: usize, mu |body: &mut Vec| list_names(body, name) == total && place_declaration(body, name, ty, total, mutable); match &mut stmts[i].kind { StmtKind::If { then, els, .. } => place(then) || place(els), - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => place(body), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => place(body), StmtKind::Catch { body, handler, .. } => place(body) || place(handler), StmtKind::Switch { cases, default, .. } => cases.iter_mut().any(|(_, body)| place(body)) || place(default), _ => false, @@ -2763,7 +2771,7 @@ fn visit_stmt(stmt: &Stmt, f: &mut dyn FnMut(&Expr)) { f(cond); then.iter().chain(els).for_each(|s| visit_stmt(s, f)); } - StmtKind::While { cond: e, body, .. } => { + StmtKind::While { cond: e, body, .. } | StmtKind::ForOf { iter: e, body, .. } => { f(e); body.iter().for_each(|s| visit_stmt(s, f)); } @@ -2950,7 +2958,9 @@ fn drop_self_assignments(stmts: &mut Vec) { drop_self_assignments(then); drop_self_assignments(els); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => drop_self_assignments(body), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + drop_self_assignments(body) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| drop_self_assignments(body)); drop_self_assignments(default); @@ -2990,7 +3000,9 @@ fn return_in_place(stmts: &mut Vec, caught: &FxHashSet) { return_in_place(then, caught); return_in_place(els, caught); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => return_in_place(body, caught), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + return_in_place(body, caught) + } StmtKind::Switch { cases, default, .. } => { cases.iter_mut().for_each(|(_, body)| return_in_place(body, caught)); return_in_place(default, caught); @@ -3067,7 +3079,9 @@ fn handler_reads(stmts: &[Stmt], out: &mut Vec) { handler_reads(then, out); handler_reads(els, out); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => handler_reads(body, out), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + handler_reads(body, out) + } StmtKind::Switch { cases, default, .. } => { cases.iter().for_each(|(_, body)| handler_reads(body, out)); handler_reads(default, out); @@ -3131,7 +3145,9 @@ fn breaks_to_return(stmts: &mut [Stmt], label: &str, ret: &Stmt) { breaks_to_return(then, label, ret); breaks_to_return(els, label, ret); } - StmtKind::While { body, .. } | StmtKind::Block { body, .. } => breaks_to_return(body, label, ret), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + breaks_to_return(body, label, ret) + } StmtKind::Switch { cases, default, .. } => { cases .iter_mut() diff --git a/ts/src/lower/mir/step.rs b/ts/src/lower/mir/step.rs index 82adb926c..3b6ef3eeb 100644 --- a/ts/src/lower/mir/step.rs +++ b/ts/src/lower/mir/step.rs @@ -331,3 +331,194 @@ pub(super) fn stepped_field(it: &Expr, key: &str) -> Expr { it => it.clone().member(key), } } + +/// Each loop over an array iterator stepped in place that only the loop steps, as +/// `for (const item of array)`: a `while (true)` whose first statements take the next +/// item and leave on `rt.DONE`. Nothing else names the index, so nothing sees where it +/// stopped. +pub(super) fn for_of(stmts: &mut Vec) { + let mut names: FxHashMap = FxHashMap::default(); + for stmt in stmts.iter() { + super::visit_stmt(stmt, &mut |e| { + super::visit_expr(e, &mut |e| { + if let Expr::Ident(name) = e { + *names.entry(name.clone()).or_default() += 1; + } + }) + }); + } + // The variables declared `= 0`, as an index starts. + let mut zeros = FxHashSet::default(); + decls(stmts, &mut |name, init| { + if matches!(init, Expr::Lit(l) if l == "0") { + zeros.insert(name.to_string()); + } + }); + let mut indexes = FxHashSet::default(); + loops(stmts, &names, &zeros, &mut indexes); + if !indexes.is_empty() { + drop_decls(stmts, &indexes); + } +} + +/// Call `f` on the name and value of each declaration in `stmts` that has one. +fn decls(stmts: &[Stmt], f: &mut dyn FnMut(&str, &Expr)) { + for stmt in stmts { + match &stmt.kind { + StmtKind::Decl { + name, init: Some(init), .. + } => f(name, init), + StmtKind::If { then, els, .. } => { + decls(then, f); + decls(els, f); + } + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + decls(body, f) + } + StmtKind::Switch { cases, default, .. } => { + cases.iter().for_each(|(_, body)| decls(body, f)); + decls(default, f); + } + StmtKind::Catch { body, handler, .. } => { + decls(body, f); + decls(handler, f); + } + _ => {} + } + } +} + +/// Rewrite the loops in `stmts`, collecting the indexes they no longer read. +fn loops( + stmts: &mut [Stmt], + names: &FxHashMap, + zeros: &FxHashSet, + indexes: &mut FxHashSet, +) { + for stmt in stmts.iter_mut() { + // The array and the index are declared, and named only by this loop's header. + if let StmtKind::While { label, cond, body } = &mut stmt.kind + && matches!(cond, Expr::Lit(l) if l == "true") + && let Some((item, array, index)) = header(body, label.as_deref()) + && names.get(&array) == Some(&2) + && names.get(&index) == Some(&2) + && zeros.contains(&index) + { + let mut body: Vec = std::mem::take(body).into_iter().skip(2).collect(); + let mut name = item; + // `const entry = item;` names the item, when nothing else reads it. + if let Some(StmtKind::Decl { + mutable: false, + name: to, + init: Some(Expr::Ident(from)), + .. + }) = body.first().map(|s| &s.kind) + && *from == name + && super::list_names(&body, &name) == 1 + { + name = to.clone(); + body.remove(0); + } + indexes.insert(index); + stmt.kind = StmtKind::ForOf { + label: label.take(), + name, + iter: Expr::ident(array), + body, + }; + } + match &mut stmt.kind { + StmtKind::If { then, els, .. } => { + loops(then, names, zeros, indexes); + loops(els, names, zeros, indexes); + } + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + loops(body, names, zeros, indexes) + } + StmtKind::Switch { cases, default, .. } => { + cases + .iter_mut() + .for_each(|(_, body)| loops(body, names, zeros, indexes)); + loops(default, names, zeros, indexes); + } + StmtKind::Catch { body, handler, .. } => { + loops(body, names, zeros, indexes); + loops(handler, names, zeros, indexes); + } + _ => {} + } + } +} + +/// The item, array, and index of a loop that starts `const item = i < s.length ? +/// s[i++] : rt.DONE; if (item === rt.DONE) break;`, the `break` leaving it. +fn header(body: &[Stmt], label: Option<&str>) -> Option<(String, String, String)> { + let [next, test, ..] = body else { + return None; + }; + let StmtKind::Decl { + mutable: false, + name: item, + init: Some(init), + .. + } = &next.kind + else { + return None; + }; + let Expr::Cond(c, a, b) = peel(init) else { + return None; + }; + let (Expr::Binary(i, "<", len), Expr::Index(s, at), Expr::Rt(done)) = (peel(c), peel(a), peel(b)) else { + return None; + }; + let (Expr::Ident(index), Expr::Member(s2, Key::Name(length)), Expr::Ident(array), Expr::Postfix(i2, "++")) = + (peel(i), peel(len), peel(s), peel(at)) + else { + return None; + }; + let same = |e: &Expr, name: &str| matches!(peel(e), Expr::Ident(n) if n == name); + if done != "DONE" || length != "length" || !same(s2, array) || !same(i2, index) { + return None; + } + let StmtKind::If { cond, then, els } = &test.kind else { + return None; + }; + let leaves = matches!(then.as_slice(), [Stmt { kind: StmtKind::Break(target), .. }] + if target.is_none() || target.as_deref() == label); + let tests = matches!(peel(cond), Expr::Binary(l, "===", r) + if same(l, item) && matches!(peel(r), Expr::Rt(d) if d == "DONE")); + (leaves && tests && els.is_empty()).then(|| (item.clone(), array.clone(), index.clone())) +} + +/// `e` without its source location. +pub(super) fn peel(e: &Expr) -> &Expr { + match e { + Expr::Located(_, e) => peel(e), + e => e, + } +} + +/// Drop the declarations of `names`, which nothing reads any more. +fn drop_decls(stmts: &mut Vec, names: &FxHashSet) { + stmts.retain(|s| !matches!(&s.kind, StmtKind::Decl { name, .. } if names.contains(name))); + for stmt in stmts.iter_mut() { + match &mut stmt.kind { + StmtKind::If { then, els, .. } => { + drop_decls(then, names); + drop_decls(els, names); + } + StmtKind::Block { body, .. } | StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => { + drop_decls(body, names) + } + StmtKind::Switch { cases, default, .. } => { + cases.iter_mut().for_each(|(_, body)| drop_decls(body, names)); + drop_decls(default, names); + } + StmtKind::Catch { body, handler, .. } => { + drop_decls(body, names); + drop_decls(handler, names); + } + _ => {} + } + } +} diff --git a/ts/src/print.rs b/ts/src/print.rs index 1d05f2eac..cda3e9204 100644 --- a/ts/src/print.rs +++ b/ts/src/print.rs @@ -313,8 +313,8 @@ impl Refs { self.stmts(program, then); self.stmts(program, els); } - StmtKind::While { cond, body, .. } => { - self.expr(program, cond); + StmtKind::While { cond: e, body, .. } | StmtKind::ForOf { iter: e, body, .. } => { + self.expr(program, e); self.stmts(program, body); } StmtKind::Block { body, .. } => self.stmts(program, body), @@ -746,6 +746,21 @@ impl Printer<'_> { self.start(); self.write("}\n"); } + StmtKind::ForOf { + label, + name, + iter, + body, + } => { + self.label(label); + let name = self.local(name).to_string(); + self.write(&format!("for (const {name} of ")); + self.expr(iter, 2); + self.write(") {\n"); + self.block_body(body); + self.start(); + self.write("}\n"); + } StmtKind::Block { label, body } => { self.label(label); self.write("{\n"); @@ -1155,6 +1170,11 @@ fn collect_locals(stmts: &[Stmt], out: &mut Vec) { collect_expr_locals(cond, out); collect_locals(body, out); } + StmtKind::ForOf { name, iter, body, .. } => { + out.push(name.clone()); + collect_expr_locals(iter, out); + collect_locals(body, out); + } StmtKind::Block { body, .. } => collect_locals(body, out), StmtKind::Catch { body, name, handler } => { collect_locals(body, out); diff --git a/ts/src/ts.rs b/ts/src/ts.rs index d88ba77a1..f95469f25 100644 --- a/ts/src/ts.rs +++ b/ts/src/ts.rs @@ -200,6 +200,13 @@ pub enum StmtKind { cond: Expr, body: Vec, }, + /// `for (const name of iter) body`, over an array. + ForOf { + label: Option, + name: String, + iter: Expr, + body: Vec, + }, Block { label: Option, body: Vec, @@ -280,7 +287,7 @@ fn breaks_out(stmts: &[Stmt], label: Option<&str>, nested: bool) -> bool { StmtKind::Switch { cases, default, .. } => { cases.iter().any(|(_, body)| breaks_out(body, label, true)) || breaks_out(default, label, true) } - StmtKind::While { body, .. } => breaks_out(body, label, true), + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } => breaks_out(body, label, true), _ => false, }) } From ee97a90de323aed7536dfedabd655e18cd0152fa Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:32:18 -0700 Subject: [PATCH 08/15] chore(quest): narrow ts-mir-size to the codec's gzipped gap Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 2 +- quest/m2/ts-mir-size.md | 25 ++++++++++++------------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/quest/m2/README.md b/quest/m2/README.md index 36996ca94..207a4c4ae 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -27,7 +27,7 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); ## Required - [Cheaper byte slices](/quest/m2/ts-byte-views.md) - splitting a `&[u8]` stops making a `Uint8Array` view per split -- [Smaller output from MIR](/quest/m2/ts-mir-size.md) - the bench's bundles shrink back to THIR's sizes, coroutine classes first +- [Smaller output from MIR](/quest/m2/ts-mir-size.md) - the codec bundle shrinks back to THIR's gzipped size - [Time Timestamp's checked_add and Ord](/quest/m2/ts-bench-timestamp.md) - the `u128` paths #89 sped up get a Chrome timing - [Time the minified bundles](/quest/m2/ts-bench-minified.md) - `just ts bench` times what it measures for size, as consumers ship it - [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - every value that drops in moq-net and kio drops where Rust drops it diff --git a/quest/m2/ts-mir-size.md b/quest/m2/ts-mir-size.md index ebc6a75cd..bd49a80c5 100644 --- a/quest/m2/ts-mir-size.md +++ b/quest/m2/ts-mir-size.md @@ -1,4 +1,4 @@ -# [M] Smaller output from MIR +# [S] Smaller output from MIR ## Goal @@ -8,20 +8,19 @@ bytes minified and 9422 gzipped, and the async handoff's at most 3458 gzipped. ## Plan -The codec's bundle is 29852 bytes minified and 9503 gzipped (+0.9% gzipped), and the -async handoff's 15053 and 3712 (+37%, +7.3%), against THIR's numbers above, built from -the same fixtures. Each candidate is measured on the bench's sizes and timings before -it lands. +[#95](https://github.com/kixelated/rust2/pull/95) brought the handoff to 3363 bytes +gzipped and the codec to 30094 minified. The codec's 9651 gzipped is what remains, +229 bytes over. -The handoff's two gaps have different sources: +That gap is the runtime, not the lowering: [#89](https://github.com/kixelated/rust2/pull/89) +grew `rt/int.ts` after THIR's numbers were taken, and THIR's own output bundled with +today's `rt/int.ts` is 31112 bytes minified and 9666 gzipped, over MIR's. Closing it +means trimming what the codec pulls from `rt/int.ts`, without losing #89's speed. -- Minified, nearly all of it is the fixture's 16 one-await `levelN` classes, about 360 - bytes each against about 135 for a THIR generator and its wrapper. Gzip folds the - copies: the 15 repeats cost 172 bytes gzipped, less than THIR's 201. -- Gzipped, the gap is the code outside the repeats: with one level each, MIR's bundle is - 284 bytes gzipped over THIR's. `drainFuture`'s `switch` dispatch, `recvFuture`, and - `register` and `wake`, whose `for` loops are stepped `while` loops with temporaries, - are where it is. +Small cuts measured by hand on the handoff and left out, each under 1% gzipped: +hoisting a dispatch's entry case out of its `switch` (3-7 bytes), dropping `unwind` +stores before a statement that can't throw (4), and merging `if` arms whose cleanup is +the same (about 15). Tried and dropped: From aae963d8b47c901bb2b18077371b5b9f012fa852 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:56:34 -0700 Subject: [PATCH 09/15] chore(quest): restate ts-mir-size's gap after #87 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-mir-size.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/quest/m2/ts-mir-size.md b/quest/m2/ts-mir-size.md index bd49a80c5..438b72dac 100644 --- a/quest/m2/ts-mir-size.md +++ b/quest/m2/ts-mir-size.md @@ -8,14 +8,17 @@ bytes minified and 9422 gzipped, and the async handoff's at most 3458 gzipped. ## Plan -[#95](https://github.com/kixelated/rust2/pull/95) brought the handoff to 3363 bytes -gzipped and the codec to 30094 minified. The codec's 9651 gzipped is what remains, -229 bytes over. - -That gap is the runtime, not the lowering: [#89](https://github.com/kixelated/rust2/pull/89) -grew `rt/int.ts` after THIR's numbers were taken, and THIR's own output bundled with -today's `rt/int.ts` is 31112 bytes minified and 9666 gzipped, over MIR's. Closing it -means trimming what the codec pulls from `rt/int.ts`, without losing #89's speed. +[#95](https://github.com/kixelated/rust2/pull/95) brought the handoff to 3424 bytes +gzipped and the codec to 30347 minified. The codec's 9744 gzipped is what remains, +322 bytes over. + +That gap came after THIR's numbers were taken, not from the lowering: +[#89](https://github.com/kixelated/rust2/pull/89) grew `rt/int.ts`, and +[#87](https://github.com/kixelated/rust2/pull/87)'s drop glue with +[#98](https://github.com/kixelated/rust2/pull/98) added 93 bytes gzipped. +THIR's own output, without those drops, bundled with #95's `rt/int.ts` is 31112 bytes +minified and 9666 gzipped. Closing the gap means trimming what the codec pulls from +`rt/int.ts` or its drop glue, without losing speed. Small cuts measured by hand on the handoff and left out, each under 1% gzipped: hoisting a dispatch's entry case out of its `switch` (3-7 bytes), dropping `unwind` From 829e4d2c478e6e0d4ae166b6a8f010f2ea1fccbf Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:05:16 -0700 Subject: [PATCH 10/15] test(ts): order a folded read after a write, and two panics Each case fails the lang differential when its rule in inline::folds is removed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/lang/expected/shapes.ts | 13 ++++++++++++- ts/fixtures/lang/src/shapes.rs | 13 ++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index e7047f513..b680e5f33 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -574,8 +574,19 @@ export function indexed(data: Uint8Array, out: rt.ByteVec): void { const _58: rt.u8 = n; n = rt.u8WrappingAdd(n, 1); slots[0] = rt.u8Add(slots[0], _58); - rt.byteVecExtendFromSlice(out, Uint8Array.of(first, second, called, f(1), slots[0], n)); + const m: Uint8Array = Uint8Array.of(at(6)); + const before: rt.u8 = m[0]; + const after: rt.u8 = rt.u8WrappingSub(increment(m), before); + rt.byteVecExtendFromSlice(out, Uint8Array.of(first, second, called, f(1), slots[0], n, after)); rt.byteVecExtendFromSlice(out, bytes); + if (rt.u8Rem(at(7), 4) === 0) { + const _96: [rt.u8, rt.u8, rt.u8] = [at(8), at(9), at(10)]; + const x: rt.u8 = _96[0]; + const y: rt.u8 = _96[1]; + const z: rt.u8 = _96[2]; + const quotient: rt.u8 = rt.u8Div(x, y); + rt.byteVecPush(out, rt.u8WrappingAdd(rt.u8Add(z, 200), quotient)); + } } /** A vector of `b`, logging that it was made. */ diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index 9990ff6b0..f884bf16d 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -609,8 +609,19 @@ fn indexed(data: &[u8], out: &mut Vec) { n = n.wrapping_add(1); 0 }] += n; - out.extend_from_slice(&[first, second, called, f(1), slots[0], n]); + // A value read before a call that changes it, used after the call's result. + let mut m = [at(6)]; + let before = m[0]; + let after = increment(&mut m).wrapping_sub(before); + out.extend_from_slice(&[first, second, called, f(1), slots[0], n, after]); out.extend_from_slice(&bytes); + // Of two operands that can panic, the one that runs first panics first. + if at(7) % 4 == 0 { + let (x, y, z) = (at(8), at(9), at(10)); + let quotient = x / y; + let sum = z + 200; + out.push(sum.wrapping_add(quotient)); + } } /// A vector of `b`, logging that it was made. From 98c12792c7d5fe4515443a579a15db386ffc7c52 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:09:40 -0700 Subject: [PATCH 11/15] test(ts): regenerate strs' snapshot for folded temporaries Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/lang/expected/strs.ts | 41 +++++++------------------------ 1 file changed, 9 insertions(+), 32 deletions(-) diff --git a/ts/fixtures/lang/expected/strs.ts b/ts/fixtures/lang/expected/strs.ts index 039300678..e39f28c69 100644 --- a/ts/fixtures/lang/expected/strs.ts +++ b/ts/fixtures/lang/expected/strs.ts @@ -51,13 +51,7 @@ export function putOffset(out: rt.ByteVec, i: rt.usize | undefined): void { /** What a predicate saw, then where it stopped. */ export function putSeen(out: rt.ByteVec, seen: rt.char[]): void { - const iterS: rt.char[] = seen; - let iterI: number = 0; - while (true) { - const _5: rt.char | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_5 === rt.DONE) { - break; - } + for (const _5 of seen) { putChar(out, _5); } rt.byteVecPush(out, 253); @@ -121,8 +115,7 @@ export function strs(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { i2 = rt.usizeAdd(i2, 1); } else { rt.byteVecPush(out, i2 & 0xff); - const _81: rt.Iter = rt.strSplit(s, String.fromCodePoint(sep)); - put(out, rt.optionUnwrapOr(rt.iterToOption(_81.next()), "none")); + put(out, rt.optionUnwrapOr(rt.iterToOption(rt.strSplit(s, String.fromCodePoint(sep)).next()), "none")); break b0; } } @@ -196,15 +189,9 @@ export function strs(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { put(out, matched); i4 = rt.usizeAdd(i4, 1); } else { - const iterS: rt.usize[] = rt.iterToArray(rt.iterMap(rt.strMatchIndices(s, "/"), (_2: [rt.usize, string]): rt.usize => { + for (const _190 of rt.iterToArray(rt.iterMap(rt.strMatchIndices(s, "/"), (_2: [rt.usize, string]): rt.usize => { return _2[0]; - })); - let iterI: number = 0; - while (true) { - const _190: rt.usize | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; - if (_190 === rt.DONE) { - break; - } + }))) { putOffset(out, _190); } break b0; @@ -213,13 +200,7 @@ export function strs(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } if (_13 === 6) { const parts3: string[] = unescape(s); - const iterS2: string[] = parts3; - let iterI2: number = 0; - while (true) { - const _202: string | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; - if (_202 === rt.DONE) { - break; - } + for (const _202 of parts3) { put(out, _202); } put(out, escape(parts3)); @@ -243,8 +224,7 @@ export function strs(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } named.name = named.name + String.fromCodePoint(_237); Named.add(named, c3); - const _246: rt.usize = rt.usizeRem(i5, 2); - const at2 = rt.idx(each, _246); + const at2 = rt.idx(each, rt.usizeRem(i5, 2)); each[at2] = each[at2] + String.fromCodePoint(c3); const _248: rt.char | undefined = rt.charFromU32(rt.u32Add(c3 as rt.u32, 1)); if (_248 !== undefined) { @@ -254,10 +234,8 @@ export function strs(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { named.name = named.name + "􏿿"; put(out, built); put(out, named.name); - const at3 = rt.idx(each, 0); - put(out, each[at3]); - const at4 = rt.idx(each, 1); - put(out, each[at4]); + put(out, each[rt.idx(each, 0)]); + put(out, each[rt.idx(each, 1)]); const before: string = built; const len: rt.usize = rt.stringLen(built); const empty: boolean = built.length === 0; @@ -292,8 +270,7 @@ export function unescape(path: string): string[] { if (ch === 47) { const taken = part; part = ""; - const _12: string = taken; - parts.push(_12); + parts.push(taken); } else if (ch === 92) { const _14: rt.char | rt.Done = chars.next(); if (_14 === rt.DONE) { From 44f089d6914469a8305c1b85b7b7907c35216a6f Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:27:26 -0700 Subject: [PATCH 12/15] fix(ts): share an upvar's field only with a copy that runs once A capture copied into a local on each pass of a loop shared the capture's field, so changing the copy changed what the next pass copied. The copy must now run at most once, in the first poll, before any other use of the local there. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/model.ts | 728 +++++++++++++++++------------ ts/fixtures/task/src/model.rs | 17 + ts/src/lower/mir/coroutine.rs | 95 +++- 3 files changed, 523 insertions(+), 317 deletions(-) diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index db955650d..d7ca065a0 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -199,6 +199,7 @@ export class blocksFuture { #awaitee$3!: rt.Future; #mark!: Mark.Mark; #nested!: Inner.Inner; + #looped!: rt.u32; #awaitee$4!: rt.Future; #saved$3!: boolean; #saved$4!: boolean; @@ -219,62 +220,73 @@ export class blocksFuture { try { b0: { b1: { - if (this.#state === 0) { - unwind = 82; - rt.drop(this.#rx); - unwind = 0; - rt.drop(this.#guard); - return; - } - if (this.#state === 3) { - unwind = 56; - rt.drop(this.#awaitee); - unwind = 57; - rt.drop(this.#saved); - this.#saved$9 = false; - break b0; - } - if (this.#state === 4) { - unwind = 51; - rt.drop(this.#awaitee$2); - unwind = 52; - rt.drop(this.#saved); - this.#saved$8 = false; - break b1; - } - if (this.#state === 5) { - unwind = 47; - rt.drop(this.#awaitee$3); - } else if (this.#state === 6) { - unwind = 44; - rt.drop(this.#awaitee$3); - } else if (this.#state === 7) { - unwind = 37; - rt.drop(this.#awaitee$4); - unwind = 40; - rt.drop(this.#saved); - unwind = 42; - rt.drop(this.#nested); - } else { - return; + b2: { + b3: { + if (this.#state === 0) { + unwind = 89; + rt.drop(this.#rx); + unwind = 0; + rt.drop(this.#guard); + return; + } + if (this.#state === 3) { + unwind = 63; + rt.drop(this.#awaitee); + unwind = 64; + rt.drop(this.#saved); + this.#saved$9 = false; + break b0; + } + if (this.#state === 4) { + unwind = 58; + rt.drop(this.#awaitee$2); + unwind = 59; + rt.drop(this.#saved); + this.#saved$8 = false; + break b1; + } + if (this.#state === 5) { + unwind = 54; + rt.drop(this.#awaitee$3); + break b2; + } + if (this.#state === 6) { + unwind = 51; + rt.drop(this.#awaitee$3); + break b3; + } + if (this.#state === 7) { + unwind = 44; + rt.drop(this.#awaitee$3); + } else if (this.#state === 8) { + unwind = 41; + rt.drop(this.#awaitee$4); + } else { + return; + } + unwind = 47; + rt.drop(this.#saved); + unwind = 49; + rt.drop(this.#nested); + } } this.#saved$7 = false; } - unwind = 55; + unwind = 62; rt.dropAll(this.#slots); } if (this.#saved$4) { - unwind = 60; + unwind = 67; rt.drop(this.#second); } this.#saved$4 = false; if (this.#saved$5) { - unwind = 61; + unwind = 68; rt.drop(this.#first); } this.#saved$5 = false; if (this.#saved$3) { - unwind = 62; + unwind = 69; rt.drop(this.#guard); } this.#saved$3 = false; @@ -284,67 +296,72 @@ export class blocksFuture { } this.#saved$6 = false; } catch (e) { - b8: { - b9: { - b10: { - b11: { - b12: { - b13: { - b14: { - b15: { - b16: { - b17: { - b18: { - b19: { - if (unwind === 0) { - throw e; - } - if (unwind === 37) { - rt.drop(this.#saved); - break b18; - } - if (unwind === 40) { - break b18; - } - if (unwind === 42) { - break b17; - } - if (unwind === 44) { - break b16; - } - if (unwind === 47) { - break b15; - } - if (unwind === 51) { - rt.drop(this.#saved); - break b19; - } - if (unwind === 52) { - break b19; - } - if (unwind === 55) { - break b13; - } - if (unwind === 56) { - rt.drop(this.#saved); - } else if (unwind !== 57) { - if (unwind === 60) { - break b11; + b9: { + b10: { + b11: { + b12: { + b13: { + b14: { + b15: { + b16: { + b17: { + b18: { + b19: { + b20: { + b21: { + if (unwind === 0) { + throw e; + } + if (unwind === 41) { + break b20; + } + if (unwind === 44) { + break b20; } - if (unwind === 61) { - break b10; + if (unwind === 47) { + break b19; + } + if (unwind === 49) { + break b18; + } + if (unwind === 51) { + break b17; + } + if (unwind === 54) { + break b16; + } + if (unwind === 58) { + rt.drop(this.#saved); + break b21; + } + if (unwind === 59) { + break b21; } if (unwind === 62) { + break b14; + } + if (unwind === 63) { + rt.drop(this.#saved); + } else if (unwind !== 64) { + if (unwind === 67) { + break b12; + } + if (unwind === 68) { + break b11; + } + if (unwind === 69) { + break b10; + } + rt.drop(this.#guard); break b9; } - rt.drop(this.#guard); - break b8; + this.#saved$9 = false; + break b13; } - this.#saved$9 = false; - break b12; + this.#saved$8 = false; + break b15; } - this.#saved$8 = false; - break b14; + rt.drop(this.#saved); } rt.drop(this.#nested); } @@ -390,294 +407,324 @@ export class blocksFuture { b1: { b2: { b3: { - if (this.#state === 0) { - unwind = 132; - this.#saved$6 = false; - this.#saved$3 = false; - this.#saved$5 = false; - this.#saved$4 = false; - this.#saved$9 = false; - this.#saved$8 = false; - this.#saved$7 = false; - this.#saved$6 = true; - this.#saved$3 = true; - this.#first = Guard.new(rt.u32Add(this.#guard.id, 200), Log.clone$Clone(this.#guard.log)); - unwind = 131; - this.#saved$5 = true; - this.#second = Guard.new(rt.u32Add(this.#guard.id, 300), Log.clone$Clone(this.#guard.log)); - unwind = 142; - this.#saved$4 = true; - rt.drop(new blocksFuture$2(this.#first)); - turns(this.#guard.log, rt.u32Rem(this.#guard.id, 5)); - temporaries(this.#guard.log, this.#guard.id); - unwind = 130; - this.#saved = Guard.new(rt.u32Add(this.#guard.id, 900), Log.clone$Clone(this.#guard.log)); - unwind = 128; - this.#saved$9 = true; - this.#awaitee = new recvFuture(this.#rx); - } else if (this.#state === 1) { - rt.asyncFnResumed(); - } else if (this.#state === 2) { - rt.asyncFnResumedPanic(); - } else if (this.#state !== 3) { - if (this.#state === 4) { - break b3; - } - if (this.#state === 5) { - break b2; + b4: { + if (this.#state === 0) { + unwind = 148; + this.#saved$6 = false; + this.#saved$3 = false; + this.#saved$5 = false; + this.#saved$4 = false; + this.#saved$9 = false; + this.#saved$8 = false; + this.#saved$7 = false; + this.#saved$6 = true; + this.#saved$3 = true; + this.#first = Guard.new(rt.u32Add(this.#guard.id, 200), Log.clone$Clone(this.#guard.log)); + unwind = 147; + this.#saved$5 = true; + this.#second = Guard.new(rt.u32Add(this.#guard.id, 300), Log.clone$Clone(this.#guard.log)); + unwind = 158; + this.#saved$4 = true; + rt.drop(new blocksFuture$2(this.#first)); + turns(this.#guard.log, rt.u32Rem(this.#guard.id, 5)); + temporaries(this.#guard.log, this.#guard.id); + unwind = 146; + this.#saved = Guard.new(rt.u32Add(this.#guard.id, 900), Log.clone$Clone(this.#guard.log)); + unwind = 144; + this.#saved$9 = true; + this.#awaitee = new recvFuture(this.#rx); + } else if (this.#state === 1) { + rt.asyncFnResumed(); + } else if (this.#state === 2) { + rt.asyncFnResumedPanic(); + } else if (this.#state !== 3) { + if (this.#state === 4) { + break b4; + } + if (this.#state === 5) { + break b3; + } + if (this.#state === 6) { + break b2; + } + if (this.#state === 7) { + break b1; + } + break b0; } - if (this.#state === 6) { - break b1; + unwind = 141; + const _32: rt.Poll = this.#awaitee.poll(_2); + if (_32 !== rt.Pending) { + unwind = 142; + const result: rt.u64 | undefined = _32; + rt.drop(this.#awaitee); + this.#saved$9 = false; + this.#waited = consume(this.#saved, result); + unwind = 158; + this.#saved$9 = false; + _40 = Guard.new(rt.u32Add(this.#guard.id, 910), Log.clone$Clone(this.#guard.log)); + unwind = 140; + const _46: Guard.Guard = Guard.new(rt.u32Add(this.#guard.id, 920), Log.clone$Clone(this.#guard.log)); + unwind = 138; + this.#slots = [_40, _46]; + this.#saved = Guard.new(rt.u32Add(this.#guard.id, 930), Log.clone$Clone(this.#guard.log)); + unwind = 136; + this.#saved$8 = true; + this.#awaitee$2 = new slotFuture(this.#rx, this.#slots.length); + } else { + this.#state = 3; + return rt.Pending; } - break b0; } - unwind = 125; - const _32: rt.Poll = this.#awaitee.poll(_2); - if (_32 !== rt.Pending) { - unwind = 126; - const result: rt.u64 | undefined = _32; - rt.drop(this.#awaitee); - this.#saved$9 = false; - this.#waited = consume(this.#saved, result); - unwind = 142; - this.#saved$9 = false; - _40 = Guard.new(rt.u32Add(this.#guard.id, 910), Log.clone$Clone(this.#guard.log)); - unwind = 124; - const _46: Guard.Guard = Guard.new(rt.u32Add(this.#guard.id, 920), Log.clone$Clone(this.#guard.log)); - unwind = 122; - this.#slots = [_40, _46]; - this.#saved = Guard.new(rt.u32Add(this.#guard.id, 930), Log.clone$Clone(this.#guard.log)); - unwind = 120; - this.#saved$8 = true; - this.#awaitee$2 = new slotFuture(this.#rx, this.#slots.length); + unwind = 134; + const _63: rt.Poll = this.#awaitee$2.poll(_2); + if (_63 !== rt.Pending) { + unwind = 155; + result2 = _63; + rt.drop(this.#awaitee$2); + if (!(result2 < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + result2); + } + unwind = 44; + rt.drop(this.#slots[result2]); + unwind = 139; + this.#saved$8 = false; + this.#slots[result2] = this.#saved; + this.#saved$8 = false; + const arg = ([this.#waited] as [rt.u64])[0]; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(arg, f)]; + const _78: string = rt.fmtFormat(["slot after ", args2[0]]); + unwind = 133; + Guard.note(this.#slots[0], _78); + unwind = 153; + this.#tally = { n: this.#guard.id }; + this.#saved$7 = true; + seen = new blocksFuture$3(copy$Tally(this.#tally)); + this.#tally.n = rt.u32Add(this.#tally.n, 1000); + this.#saved = this.#guard; + this.#saved$2 = this.#tally.n; + this.#saved$7 = false; + this.#awaitee$3 = seen; } else { - this.#state = 3; + this.#state = 4; return rt.Pending; } } - unwind = 118; - const _63: rt.Poll = this.#awaitee$2.poll(_2); - if (_63 !== rt.Pending) { - unwind = 139; - result2 = _63; - rt.drop(this.#awaitee$2); - if (!(result2 < 2)) { - rt.panic("index out of bounds: the len is " + 2 + " but the index is " + result2); - } - unwind = 44; - rt.drop(this.#slots[result2]); - unwind = 123; - this.#saved$8 = false; - this.#slots[result2] = this.#saved; - this.#saved$8 = false; - const arg = ([this.#waited] as [rt.u64])[0]; - const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(arg, f)]; - const _78: string = rt.fmtFormat(["slot after ", args2[0]]); - unwind = 117; - Guard.note(this.#slots[0], _78); - unwind = 137; - this.#tally = { n: this.#guard.id }; - this.#saved$7 = true; - seen = new blocksFuture$3(copy$Tally(this.#tally)); - this.#tally.n = rt.u32Add(this.#tally.n, 1000); - this.#saved = this.#guard; - this.#saved$2 = this.#tally.n; - this.#saved$7 = false; - this.#awaitee$3 = seen; + unwind = 131; + const _101: rt.Poll = this.#awaitee$3.poll(_2); + if (_101 !== rt.Pending) { + unwind = 153; + const _98: rt.u32 = _101; + rt.drop(this.#awaitee$3); + const arg2 = this.#saved$2; + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f), (f: rt.Formatter) => rt.u32Display(_98, f)]; + const _93: string = rt.fmtFormat(["tally ", args4[0], " then ", args4[1]]); + unwind = 130; + Guard.note(this.#saved, _93); + unwind = 153; + this.#mark = { n: 1 }; + this.#awaitee$3 = new blocksFuture$4(this.#mark); } else { - this.#state = 4; + this.#state = 5; return rt.Pending; } } - unwind = 115; - const _101: rt.Poll = this.#awaitee$3.poll(_2); - if (_101 !== rt.Pending) { - unwind = 137; - const _98: rt.u32 = _101; + unwind = 129; + const _117: rt.Poll = this.#awaitee$3.poll(_2); + if (_117 !== rt.Pending) { + unwind = 153; + this.#saved$2 = _117; rt.drop(this.#awaitee$3); - const arg2 = this.#saved$2; - const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f), (f: rt.Formatter) => rt.u32Display(_98, f)]; - const _93: string = rt.fmtFormat(["tally ", args4[0], " then ", args4[1]]); - unwind = 114; - Guard.note(this.#saved, _93); - unwind = 137; - this.#mark = { n: 1 }; - this.#awaitee$3 = new blocksFuture$4(this.#mark); + const arg3 = this.#saved$2; + const _136: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg3, f); + const arg4 = this.#mark.n; + const args6: rt.Fmt[] = [_136, (f: rt.Formatter) => rt.u32Display(arg4, f)]; + const _129: string = rt.fmtFormat(["mark ", args6[0], " ", args6[1]]); + unwind = 128; + Guard.note(this.#guard, _129); + unwind = 127; + _141 = undefined; + const _142: Guard.Guard = Guard.new(rt.u32Add(this.#guard.id, 800), Log.clone$Clone(this.#guard.log)); + unwind = 153; + const _149: Outer.Outer = new Outer.Outer({ inner: _141, guard: _142 }); + unwind = 126; + this.#nested = new Inner.Inner({ outer: _149 }); + const third: Guard.Guard = Guard.new(rt.u32Add(this.#guard.id, 400), Log.clone$Clone(this.#guard.log)); + if (!this.#moves) { + this.#saved = third; + } else { + this.#saved = third; + } + unwind = 125; + Guard.note(this.#saved, "chosen"); + this.#awaitee$3 = new blocksFuture$5(this.#guard.id); } else { - this.#state = 5; + this.#state = 6; return rt.Pending; } } - unwind = 113; - const _117: rt.Poll = this.#awaitee$3.poll(_2); - if (_117 !== rt.Pending) { - unwind = 137; - this.#saved$2 = _117; + unwind = 124; + const _162: rt.Poll = this.#awaitee$3.poll(_2); + if (_162 !== rt.Pending) { + unwind = 125; + this.#looped = _162; rt.drop(this.#awaitee$3); - const arg3 = this.#saved$2; - const _136: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg3, f); - const arg4 = this.#mark.n; - const args6: rt.Fmt[] = [_136, (f: rt.Formatter) => rt.u32Display(arg4, f)]; - const _129: string = rt.fmtFormat(["mark ", args6[0], " ", args6[1]]); - unwind = 112; - Guard.note(this.#guard, _129); - unwind = 111; - _141 = undefined; - const _142: Guard.Guard = Guard.new(rt.u32Add(this.#guard.id, 800), Log.clone$Clone(this.#guard.log)); - unwind = 137; - const _149: Outer.Outer = new Outer.Outer({ inner: _141, guard: _142 }); - unwind = 110; - this.#nested = new Inner.Inner({ outer: _149 }); - const third: Guard.Guard = Guard.new(rt.u32Add(this.#guard.id, 400), Log.clone$Clone(this.#guard.log)); - if (!this.#moves) { - this.#saved = third; - } else { - this.#saved = third; - } - unwind = 109; - Guard.note(this.#saved, "chosen"); + const arg5 = ([this.#looped] as [rt.u32])[0]; + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg5, f)]; + const _174: string = rt.fmtFormat(["looped ", args8[0]]); + unwind = 123; + Guard.note(this.#saved, _174); if (this.#moves) { + unwind = 125; this.#saved$3 = false; - rt.drop(new blocksFuture$5(this.#guard)); + rt.drop(new blocksFuture$7(this.#guard)); } + unwind = 125; this.#saved$5 = false; this.#saved$4 = false; this.#saved$6 = false; - this.#awaitee$4 = new blocksFuture$6(this.#first, this.#second, this.#rx); + this.#awaitee$4 = new blocksFuture$8(this.#first, this.#second, this.#rx); } else { - this.#state = 6; + this.#state = 7; return rt.Pending; } } - unwind = 108; - const _164: rt.Poll = this.#awaitee$4.poll(_2); - if (_164 !== rt.Pending) { - unwind = 109; - const result5: rt.u64 = _164; + unwind = 122; + const _188: rt.Poll = this.#awaitee$4.poll(_2); + if (_188 !== rt.Pending) { + unwind = 125; + const result6: rt.u64 = _188; rt.drop(this.#awaitee$4); - unwind = 110; + unwind = 126; rt.drop(this.#saved); - unwind = 137; + unwind = 153; rt.drop(this.#nested); - unwind = 142; + unwind = 158; this.#saved$7 = false; rt.dropAll(this.#slots); this.#saved$4 = false; this.#saved$5 = false; if (this.#saved$3) { - unwind = 133; + unwind = 149; rt.drop(this.#guard); } this.#saved$3 = false; this.#saved$6 = false; this.#state = 1; - return result5; + return result6; } - this.#state = 7; + this.#state = 8; return rt.Pending; } catch (e) { - b8: { - b9: { - b10: { - b11: { - b12: { - b13: { - b14: { - b15: { - b16: { + b9: { + b10: { + b11: { + b12: { + b13: { + b14: { + b15: { + b16: { + b17: { if (unwind === 0) { throw e; } if (unwind === 44) { this.#saved$8 = false; this.#slots[result2] = this.#saved; - break b13; + break b14; } - if (unwind === 108) { + if (unwind === 122) { rt.drop(this.#awaitee$4); - break b16; + break b17; } - if (unwind === 109) { - break b16; + if (unwind === 123) { + break b17; } - if (unwind === 110) { - break b15; + if (unwind === 124) { + rt.drop(this.#awaitee$3); + break b17; } - if (unwind === 111) { + if (unwind === 125) { + break b17; + } + if (unwind === 126) { + break b16; + } + if (unwind === 127) { rt.drop(_141); - break b14; + break b15; } - if (unwind === 112) { - break b14; + if (unwind === 128) { + break b15; } - if (unwind === 113) { + if (unwind === 129) { rt.drop(this.#awaitee$3); - break b14; + break b15; } - if (unwind === 114) { - break b14; + if (unwind === 130) { + break b15; } - if (unwind === 115) { + if (unwind === 131) { rt.drop(this.#awaitee$3); - break b14; + break b15; } - if (unwind === 117) { - break b12; + if (unwind === 133) { + break b13; } - if (unwind === 118) { + if (unwind === 134) { rt.drop(this.#awaitee$2); - break b13; + break b14; } - if (unwind === 120) { + if (unwind === 136) { rt.drop(this.#saved); this.#saved$8 = false; - break b12; + break b13; } - if (unwind === 122) { + if (unwind === 138) { this.#saved$8 = false; - break b12; + break b13; } - if (unwind === 123) { - break b12; + if (unwind === 139) { + break b13; } - if (unwind === 124) { + if (unwind === 140) { rt.drop(_40); - break b11; + break b12; } - if (unwind === 125) { + if (unwind === 141) { rt.drop(this.#awaitee); - } else if (unwind !== 126) { - if (unwind === 128) { + } else if (unwind !== 142) { + if (unwind === 144) { rt.drop(this.#saved); this.#saved$9 = false; - break b11; + break b12; } - if (unwind === 130) { + if (unwind === 146) { this.#saved$9 = false; + break b12; + } + if (unwind === 147) { break b11; } - if (unwind === 131) { + if (unwind === 148) { break b10; } - if (unwind === 132) { + if (unwind === 149) { break b9; } - if (unwind === 133) { - break b8; + if (unwind === 153) { + break b15; } - if (unwind === 137) { + if (unwind === 155) { break b14; } - if (unwind === 139) { - break b13; - } - break b11; + break b12; } if (this.#saved$9) { rt.drop(this.#saved); } this.#saved$9 = false; - break b11; + break b12; } rt.drop(this.#saved); } @@ -687,7 +734,7 @@ export class blocksFuture { rt.drop(seen); } this.#saved$7 = false; - break b12; + break b13; } if (this.#saved$8) { rt.drop(this.#saved); @@ -815,6 +862,99 @@ export class blocksFuture$4 { } export class blocksFuture$5 { + #state: number = 0; + #base: rt.u32; + #total!: rt.u32; + #passes!: rt.i32; + #x!: rt.u32; + #awaitee!: rt.Future; + + constructor(base: rt.u32) { + this.#base = base; + } + + [Symbol.dispose](): void { + if (this.#state === 3) { + rt.drop(this.#awaitee); + } + } + + poll(_2: rt.Context): rt.Poll { + let unwind: number = 0; + try { + let bb0: number = 0; + while (true) { + switch (bb0) { + case 0: + if (this.#state === 0) { + this.#total = 0; + this.#passes = 0; + bb0 = 1; + continue; + } + if (this.#state === 1) { + rt.asyncFnResumed(); + } else if (this.#state === 2) { + rt.asyncFnResumedPanic(); + } else { + bb0 = 5; + continue; + } + case 1: + if (!(this.#passes < 2)) { + const _0: rt.Poll = this.#total; + this.#state = 1; + return _0; + } + unwind = 17; + this.#x = this.#base; + this.#x = rt.u32Add(this.#x, 1); + this.#awaitee = new blocksFuture$6(); + bb0 = 5; + continue; + case 5: + unwind = 16; + if (this.#awaitee.poll(_2) !== rt.Pending) { + unwind = 17; + rt.drop(this.#awaitee); + this.#total = rt.u32Add(this.#total, this.#x); + this.#passes = rt.i32Add(this.#passes, 1); + bb0 = 1; + continue; + } + this.#state = 3; + return rt.Pending; + } + } + } catch (e) { + if (unwind === 0) { + throw e; + } + if (unwind === 16) { + rt.drop(this.#awaitee); + } + this.#state = 2; + throw e; + } + } +} + +export class blocksFuture$6 { + #state: number = 0; + + [Symbol.dispose](): void { + } + + poll(_2: rt.Context): rt.Poll { + if (this.#state === 0) { + this.#state = 1; + return undefined; + } + rt.asyncFnResumed(); + } +} + +export class blocksFuture$7 { #state: number = 0; #guard: Guard.Guard; @@ -857,7 +997,7 @@ export class blocksFuture$5 { } } -export class blocksFuture$6 { +export class blocksFuture$8 { #state: number = 0; #first: Guard.Guard; #second: Guard.Guard; diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index 7f524ff16..33aaba0ad 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -161,6 +161,23 @@ pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { false => third, }; chosen.note("chosen"); + // A capture copied into a local on each pass of a loop, which then changes the copy: + // the next pass copies the capture unchanged. + let base = guard.id; + let looped = async move { + let mut total = 0; + let mut passes = 0; + while passes < 2 { + let mut x = base; + x += 1; + async {}.await; + total += x; + passes += 1; + } + total + } + .await; + chosen.note(&format!("looped {looped}")); if moves { drop(async move { guard.note("moved") }); } diff --git a/ts/src/lower/mir/coroutine.rs b/ts/src/lower/mir/coroutine.rs index 3a48def82..9143cd50a 100644 --- a/ts/src/lower/mir/coroutine.rs +++ b/ts/src/lower/mir/coroutine.rs @@ -4,7 +4,7 @@ //! transform made, which drops what the state it is in holds. use rustc_abi::{FieldIdx, VariantIdx}; -use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::def_id::DefId; use rustc_index::IndexVec; use rustc_middle::mir::{self, CoroutineSavedLocal, Operand}; @@ -291,22 +291,25 @@ pub fn construct<'tcx>( } /// The saved locals the resume function `mir` of the coroutine `def_id` moves or copies -/// an upvar into, with the upvar's index, where that is the upvar's one read: nothing -/// reads the upvar's field after, so the local can keep its value there. +/// an upvar into, with the upvar's index, where the local can keep its value in the +/// upvar's field: that copy is the upvar's one use and runs at most once, and it comes +/// before every other use of the local. fn moved_upvars<'tcx>( mir: &mir::Body<'tcx>, def_id: DefId, layout: &mir::CoroutineLayout<'tcx>, ) -> FxHashMap { use mir::visit::{PlaceContext, Visitor}; - use mir::{ProjectionElem, Rvalue, StatementKind}; + use mir::{Location, ProjectionElem, Rvalue, StatementKind}; - struct Reads<'m, 'tcx> { + struct Uses<'m, 'tcx> { mir: &'m mir::Body<'tcx>, def_id: DefId, - reads: FxHashMap, + layout: &'m mir::CoroutineLayout<'tcx>, + upvars: FxHashMap, + locals: FxHashMap>, } - impl<'tcx> Reads<'_, 'tcx> { + impl<'tcx> Uses<'_, 'tcx> { /// The upvar `place` is, or the field of a variant, of this coroutine. fn split(&self, place: mir::Place<'tcx>) -> Option<(Option, FieldIdx)> { let ty = self.mir.local_decls[place.local].ty.builtin_deref(true)?; @@ -325,27 +328,44 @@ fn moved_upvars<'tcx>( } } } - impl<'tcx> Visitor<'tcx> for Reads<'_, 'tcx> { - fn visit_place(&mut self, place: &mir::Place<'tcx>, cx: PlaceContext, at: mir::Location) { - // Debug info names a place without reading it. - if !matches!(cx, PlaceContext::NonUse(_)) - && let Some((None, f)) = self.split(*place) - { - *self.reads.entry(f).or_default() += 1; + impl<'tcx> Visitor<'tcx> for Uses<'_, 'tcx> { + fn visit_place(&mut self, place: &mir::Place<'tcx>, cx: PlaceContext, at: Location) { + // Debug info names a place without using it. + if !matches!(cx, PlaceContext::NonUse(_)) { + match self.split(*place) { + Some((None, f)) => *self.upvars.entry(f).or_default() += 1, + Some((Some(v), f)) => self + .locals + .entry(self.layout.variant_fields[v][f]) + .or_default() + .push(at), + None => {} + } } self.super_place(place, cx, at); } } - let mut reads = Reads { + let mut uses = Uses { mir, def_id, - reads: FxHashMap::default(), + layout, + upvars: FxHashMap::default(), + locals: FxHashMap::default(), }; - reads.visit_body(mir); + uses.visit_body(mir); let mut moved = FxHashMap::default(); - for data in mir.basic_blocks.iter() { - for stmt in &data.statements { + // The transform's entry switch on the state: an unresumed coroutine's first poll + // starts at one target, and every later poll at another. + let mir::TerminatorKind::SwitchInt { targets, .. } = &mir.basic_blocks[mir::START_BLOCK].terminator().kind else { + return moved; + }; + let Some(first) = targets.iter().find(|&(state, _)| state == 0).map(|(_, b)| b) else { + return moved; + }; + let later = reach(mir, targets.all_targets().iter().copied().filter(|&b| b != first), None); + for (block, data) in mir.basic_blocks.iter_enumerated() { + for (statement_index, stmt) in data.statements.iter().enumerate() { let StatementKind::Assign(assign) = &stmt.kind else { continue; }; @@ -354,13 +374,42 @@ fn moved_upvars<'tcx>( }; if src.projection.len() == 2 && dest.projection.len() == 3 - && let Some((None, upvar)) = reads.split(*src) - && let Some((Some(variant), field)) = reads.split(*dest) - && reads.reads.get(&upvar) == Some(&1) + && let Some((None, upvar)) = uses.split(*src) + && let Some((Some(variant), field)) = uses.split(*dest) + && uses.upvars.get(&upvar) == Some(&1) + // Only the first poll copies, and only once. + && !later.contains(&block) + && !reach(mir, mir.basic_blocks[block].terminator().successors(), None).contains(&block) { - moved.insert(layout.variant_fields[variant][field], upvar.index()); + // Nothing the first poll runs before the copy, or instead of it, uses the + // local; a later poll runs after it. + let local = layout.variant_fields[variant][field]; + let around = reach(mir, [first], Some(block)); + let after = |u: &Location| match u.block == block { + true => u.statement_index >= statement_index, + false => !around.contains(&u.block), + }; + if uses.locals[&local].iter().all(after) { + moved.insert(local, upvar.index()); + } } } } moved } + +/// The blocks a run from `starts` can reach, without entering `avoid`. +fn reach( + mir: &mir::Body<'_>, + starts: impl IntoIterator, + avoid: Option, +) -> FxHashSet { + let mut seen = FxHashSet::default(); + let mut next: Vec<_> = starts.into_iter().collect(); + while let Some(b) = next.pop() { + if Some(b) != avoid && seen.insert(b) { + next.extend(mir.basic_blocks[b].terminator().successors()); + } + } + seen +} From 31ee198d3066f776988f2d1f3bad9a3e00d25345 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:37:42 -0700 Subject: [PATCH 13/15] chore(quest): restate ts-mir-size's codec gap after #82 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-mir-size.md | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/quest/m2/ts-mir-size.md b/quest/m2/ts-mir-size.md index 438b72dac..58ec3c604 100644 --- a/quest/m2/ts-mir-size.md +++ b/quest/m2/ts-mir-size.md @@ -8,17 +8,24 @@ bytes minified and 9422 gzipped, and the async handoff's at most 3458 gzipped. ## Plan -[#95](https://github.com/kixelated/rust2/pull/95) brought the handoff to 3424 bytes -gzipped and the codec to 30347 minified. The codec's 9744 gzipped is what remains, -322 bytes over. - -That gap came after THIR's numbers were taken, not from the lowering: -[#89](https://github.com/kixelated/rust2/pull/89) grew `rt/int.ts`, and -[#87](https://github.com/kixelated/rust2/pull/87)'s drop glue with -[#98](https://github.com/kixelated/rust2/pull/98) added 93 bytes gzipped. -THIR's own output, without those drops, bundled with #95's `rt/int.ts` is 31112 bytes -minified and 9666 gzipped. Closing the gap means trimming what the codec pulls from -`rt/int.ts` or its drop glue, without losing speed. +[#95](https://github.com/kixelated/rust2/pull/95) brought the handoff to 3423 bytes +gzipped. The codec is what remains: 30935 bytes minified and 9898 gzipped, 306 and 476 +over. + +That gap came after THIR's numbers were taken, not from the lowering. On the same +fixtures with #95, these PRs added to the codec: + +- [#89](https://github.com/kixelated/rust2/pull/89) grew `rt/int.ts`. THIR's own output + bundled with #95's `rt/int.ts`, before #87, is 31112 bytes minified and 9666 gzipped, + over MIR's 30094 and 9651. +- [#87](https://github.com/kixelated/rust2/pull/87)'s drop glue with + [#98](https://github.com/kixelated/rust2/pull/98) added 253 bytes minified and 93 + gzipped. +- [#82](https://github.com/kixelated/rust2/pull/82)'s `rt.ByteSlice` added 580 bytes + minified and 156 gzipped. + +Closing the gap means trimming what the codec pulls from the runtime or its drop glue, +without losing speed, or restating the goal against today's runtime. Small cuts measured by hand on the handoff and left out, each under 1% gzipped: hoisting a dispatch's entry case out of its `switch` (3-7 bytes), dropping `unwind` From b168bd3174f73e6f2b53753a2746f7d19b29e518 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:44:57 -0700 Subject: [PATCH 14/15] test(ts): regenerate shapes' snapshot after merging main Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/lang/expected/shapes.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 2ebe4ee5d..a65b779de 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -1401,8 +1401,7 @@ export function payloads(data: rt.ByteSlice, out: rt.ByteVec): void { replaced = rt.Ok(66); rt.byteVecPush(out, old); } - const _80: string = ""; - let named: rt.Result = rt.Ok(_80); + let named: rt.Result = rt.Ok(""); if (named.ok) { named = rt.Ok(named.value + "r"); } From a427c3bbd2799e1072162d006100bb00505e046d Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:07:18 -0700 Subject: [PATCH 15/15] Regenerate snapshots after merging #107 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/lang/expected/keys.ts | 12 ++++-------- ts/fixtures/lang/expected/strs.ts | 20 ++++++-------------- 2 files changed, 10 insertions(+), 22 deletions(-) diff --git a/ts/fixtures/lang/expected/keys.ts b/ts/fixtures/lang/expected/keys.ts index ed217b978..52b25ec72 100644 --- a/ts/fixtures/lang/expected/keys.ts +++ b/ts/fixtures/lang/expected/keys.ts @@ -293,8 +293,7 @@ export function defaults(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, _29 | (((order_ !== undefined && order_ >= 0 ? 1 : 0) << 7) & 0xff)); const _58: rt.u8 = compare$Option_Rough(a, b); const _67: Rough.Rough | undefined = a; - const _68: Rough.Rough | undefined = undefined; - const order2 = rt.cmpOption(Rough.partialCmp$PartialOrd)(_67, _68); + const order2 = rt.cmpOption(Rough.partialCmp$PartialOrd)(_67, undefined); const _57: rt.u8 = _58 | (((order2 !== undefined && order2 <= 0 ? 1 : 0) << 5) & 0xff); const _74: Rough.Rough | undefined = undefined; const _76: Rough.Rough | undefined = b; @@ -317,18 +316,15 @@ export function defaults(data: rt.ByteSlice, out: rt.ByteVec): void { return h3._0; }); rt.byteVecPush(out, _123 | (((rt.cmpOption(rt.cmp)(_130, _132) === 1 ? 1 : 0) << 5) & 0xff)); - const _139: boolean = rt.u8Rem(c, 2) === 0; - const _138: Horizon.Horizon = { exclude: g, local: _139 }; + const _138: Horizon.Horizon = { exclude: g, local: rt.u8Rem(c, 2) === 0 }; unwind = 0; - const _143: boolean = rt.u8Rem(d, 2) === 0; - const _137: [Horizon.Horizon, Horizon.Horizon] = [_138, { exclude: h, local: _143 }]; + const _137: [Horizon.Horizon, Horizon.Horizon] = [_138, { exclude: h, local: rt.u8Rem(d, 2) === 0 }]; const x: Horizon.Horizon = _138; const y: Horizon.Horizon = _137[1]; const _149: rt.u8 = compare$Horizon(x, y); unwind = 0; const _148: rt.u8 = _149 | (((Horizon.partialCmp$PartialOrd(x, y) === -1 ? 1 : 0) << 5) & 0xff); - const _167: Horizon.Horizon = x; - const order4 = Horizon.partialCmp$PartialOrd(_167, y); + const order4 = Horizon.partialCmp$PartialOrd(x, y); rt.byteVecPush(out, _148 | (((order4 !== undefined && order4 >= 0 ? 1 : 0) << 6) & 0xff)); _177 = name(c); unwind = 99; diff --git a/ts/fixtures/lang/expected/strs.ts b/ts/fixtures/lang/expected/strs.ts index 61e6d7afe..87f756b2f 100644 --- a/ts/fixtures/lang/expected/strs.ts +++ b/ts/fixtures/lang/expected/strs.ts @@ -276,8 +276,7 @@ export function slices(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { let _211!: [rt.usize, rt.usize]; let sliced!: string; const s: string = text(data); - const _6: string = s; - const p: string = pattern(kind, _6); + const p: string = pattern(kind, s); b0: { const _8: rt.u8 = rt.u8Rem(kind, 8); if (_8 === 0) { @@ -328,8 +327,7 @@ export function slices(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { while (true) { const _125: rt.usize | undefined = rt.strRfind(path, "/"); if (_125 !== undefined) { - const _130: string = path; - path = rt.strSlice(_130, 0, _125); + path = rt.strSlice(path, 0, _125); put(out, path); } else { break; @@ -338,14 +336,10 @@ export function slices(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { put(out, path); } else if (_8 === 4) { const keep: rt.usize = rt.usizeAdd(rt.u8Rem(rt.u8Div(kind, 8), 4) as rt.usize, 1); - const _146: rt.Iter<[rt.usize, string]> = rt.strMatchIndices(s, "/"); - const _149: rt.usize = rt.usizeSub(keep, 1); - put(out, rt.optionUnwrapOr(rt.optionMap(rt.iterNth(_146, _149), (_2: [rt.usize, string]): string => { + put(out, rt.optionUnwrapOr(rt.optionMap(rt.iterNth(rt.strMatchIndices(s, "/"), rt.usizeSub(keep, 1)), (_2: [rt.usize, string]): string => { return rt.strSlice(s, 0, _2[0]); }), "none")); - const _159: rt.Iter<[rt.usize, string]> = rt.strMatchIndices(s, "/"); - const _162: rt.usize = rt.usizeSub(keep, 1); - const part5 = rt.optionMapOr(rt.iterNth(_159, _162), rt.stringLen(s), (_22: [rt.usize, string]): rt.usize => { + const part5 = rt.optionMapOr(rt.iterNth(rt.strMatchIndices(s, "/"), rt.usizeSub(keep, 1)), rt.stringLen(s), (_22: [rt.usize, string]): rt.usize => { return rt.usizeAdd(_22[0], 1); }); put(out, rt.strSlice(s, part5)); @@ -376,11 +370,9 @@ export function slices(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } else if (_225 === 1) { sliced = rt.strSlice(s, a); } else if (_225 === 2) { - const _236: string = s; - sliced = rt.strSlice(_236, 0, b); + sliced = rt.strSlice(s, 0, b); } else { - const _240: string = s; - sliced = rt.strSlice(_240, 0); + sliced = rt.strSlice(s, 0); } put(out, sliced); }