From 4a17c6ca613b836a5f0d72db464c45473bf7b247 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 05:24:16 -0700 Subject: [PATCH 1/3] chore(quest): claim quest/m2/ts-source-order.md Quest-Claim: 675dd4e5e8d8f203 From 241673d6bfc6bb2f2d2a9ccbf60116d2ff8001bd Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 05:44:39 -0700 Subject: [PATCH 2/3] feat(ts): emit items and methods in source order, whatever reaches them first Sort each module's items, each class's or companion's methods, and each file's imports by source position, then by instance suffix and the full instance, so the order no longer depends on the order translation reaches them in. A test translates the codec fixture with and without bench::run and checks the first output's lines stay in order. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 1 - quest/m2/ts-source-order.md | 16 -------- ts/README.md | 9 ++++- ts/src/lower/mod.rs | 19 +++++---- ts/src/print.rs | 15 +++---- ts/src/program.rs | 34 +++++++++++----- ts/tests/fixtures.rs | 78 +++++++++++++++++++++++++++++++++---- 7 files changed, 119 insertions(+), 53 deletions(-) delete mode 100644 quest/m2/ts-source-order.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 2a3f40b48..131339e4d 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -22,7 +22,6 @@ deletes the quests that follow it. - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values - [Iterators](/quest/m2/ts-iter.md) - lazy `rt.ts` adaptors with a `DONE` protocol - [Collections](/quest/m2/ts-collections.md) - maps, sets, and queues keep Rust's key semantics -- [Source order](/quest/m2/ts-source-order.md) - each module's items come out in Rust source order - [Translate moq-net's model to TypeScript](/quest/m2/ts-model.md) - the driver grows from moq-net's codec to its model, for moq to compare against WASM - [Namespaced external types](/quest/m2/uniffi-namespaces.md) - two crates linked into one library can each export a same-named type in every generator - [Zero-copy byte returns](/quest/m2/ffi-bytes-return.md) - returned payloads reach the host without a copy, if the payload numbers justify it diff --git a/quest/m2/ts-source-order.md b/quest/m2/ts-source-order.md deleted file mode 100644 index e772f062b..000000000 --- a/quest/m2/ts-source-order.md +++ /dev/null @@ -1,16 +0,0 @@ -# [XS] Source order in the TypeScript translator - -## Goal - -[rust2-ts](/ts/README.md) emits each module's items in Rust source order, -whatever order it reaches them in, so adding a root changes only the output of -the code it reaches. - -## Plan - -Decided with the maintainer on 2026-10-23: source order rather than sorted by -name, so the output reads like the Rust. Adding the benchmark's entry point -(PR #7) reordered a method in the codec's `decode.ts` snapshot with no change -in behaviour. - -Public API: the order of the translator's output. diff --git a/ts/README.md b/ts/README.md index 985879d0e..0b423a222 100644 --- a/ts/README.md +++ b/ts/README.md @@ -87,6 +87,12 @@ generic class holds a method per instance, each declaring the instance it takes array, or an `Option` or `Result` holding one, is copied where Rust copies it, since JS would share the object. +A file's items, and a class's or companion's methods, follow the Rust source, whatever +order translation reaches them in, so adding a root moves nothing it does not reach. +What a macro makes sits where the macro is called. The instances of one function sit +together, sorted by their suffix (`Pair` in `fmt$Pair`) and then by their full type +arguments. + Imports name the `.ts` file, which Node, Bun, and bundlers run as is. A `tsc` build sets `rewriteRelativeImportExtensions`, or `allowImportingTsExtensions` with `noEmit`. @@ -135,7 +141,8 @@ built natively for wasm32 and run beside its translation on the same inputs by `tests/differential.ts`, which fails on any difference in output or panic messages. - `codec` vendors moq-net's sync codec, which a harness outside the crate could not reach, - and writes its errors' `Display` and `Debug`. + and writes its errors' `Display` and `Debug`. It is also translated without + `bench::run` and then with it as the first root, which must keep every line in order. - `lang` covers every integer width's arithmetic and casts, control flow, patterns, `Copy` aggregates, formatting, and methods on generic types. Its differential test runs through `caller.ts`, a hand-written caller that also prints a `printable` error nothing diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 1f1bcc162..959aa7c55 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -483,7 +483,6 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { Owner::Module => (None, SymKind::Function), }; let base = camel(tcx.item_name(def_id).as_str()); - let order = self.order(tcx.def_span(def_id)); let sym = self.program.sym(Symbol { module: self.module_of(def_id), base: match owner { @@ -493,7 +492,9 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { suffix: self.suffix(instance), owner: owner_sym, kind, - order, + order: self.order(def_id), + // Without trimmed paths, which rustc computes only for a diagnostic. + instance: ty::print::with_no_trimmed_paths!(instance.to_string()), name: String::new(), }); self.instances.insert(instance, sym); @@ -588,12 +589,10 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { .collect() } - pub fn order(&mut self, span: Span) -> (u32, u32) { - let span = span.source_callsite(); - let sm = self.tcx.sess.source_map(); - let file = sm.lookup_source_file(span.lo()); - let index = self.source(&file).unwrap_or(u32::MAX); - (index, (span.lo() - file.start_pos).0) + /// Where `def_id` is written, for sorting: where its macro is called, for an item a + /// macro makes. + fn order(&self, def_id: DefId) -> u32 { + self.tcx.def_span(def_id).source_callsite().lo().0 } fn source(&mut self, file: &rustc_span::SourceFile) -> Option { @@ -688,14 +687,14 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { AdtRepr::Class { .. } => SymKind::Class, _ => SymKind::Union { companion: false }, }; - let order = self.order(tcx.def_span(did)); let sym = self.program.sym(Symbol { module: self.module_of(did), base: tcx.item_name(did).to_string(), suffix: String::new(), owner: None, kind, - order, + order: self.order(did), + instance: String::new(), name: String::new(), }); let mut info = Adt { sym, repr }; diff --git a/ts/src/print.rs b/ts/src/print.rs index 6d1788f3d..34224b656 100644 --- a/ts/src/print.rs +++ b/ts/src/print.rs @@ -55,7 +55,7 @@ pub fn module(program: &Program, module: &ModPath, items: &[&Item], path: &Path) for (target, names) in &bindings.imports { let names: Vec = names .iter() - .map(|(sym, (binding, value))| { + .map(|(sym, binding, value)| { let name = &program.syms[*sym].name; let kind = if *value { "" } else { "type " }; match binding == name { @@ -122,9 +122,9 @@ fn relative(from: &Path, to: &Path) -> PathBuf { struct Bindings { /// A local binding for each top-level symbol the module names. names: HashMap, - /// For each module imported from: each symbol, its binding, and whether it is used as - /// a value rather than only as a type. - imports: BTreeMap>, + /// For each module imported from: each symbol, in that module's order, its binding, and + /// whether it is used as a value rather than only as a type. + imports: BTreeMap>, } impl Bindings { @@ -143,13 +143,14 @@ impl Bindings { } } - let mut imports: BTreeMap> = BTreeMap::new(); + let mut imports: BTreeMap> = BTreeMap::new(); let mut foreign: Vec<(SymId, bool)> = refs .used .into_iter() .filter(|(id, _)| &program.syms[*id].module != module) .collect(); - foreign.sort(); + let key = |id: SymId| (&program.syms[id].module, program.syms[id].key()); + foreign.sort_by(|a, b| key(a.0).cmp(&key(b.0))); for (id, value) in foreign { let sym = &program.syms[id]; let mut binding = sym.name.clone(); @@ -167,7 +168,7 @@ impl Bindings { imports .entry(sym.module.clone()) .or_default() - .insert(id, (binding, value)); + .push((id, binding, value)); } Self { names, imports } } diff --git a/ts/src/program.rs b/ts/src/program.rs index dd3799583..f6cea7b79 100644 --- a/ts/src/program.rs +++ b/ts/src/program.rs @@ -25,12 +25,24 @@ pub struct Symbol { /// The class or companion a method or field belongs to. pub owner: Option, pub kind: SymKind, - /// Where it sorts within its module: its source position. - pub order: (u32, u32), + /// Its source position in rustc's source map, which numbers files in the order it + /// loads them. + pub order: u32, + /// The function instance it is, printed in full; empty for a type. + pub instance: String, /// The final name, set by [`Program::name`]. pub name: String, } +impl Symbol { + /// Where it sorts among its module's items or its owner's methods: in source order, + /// and the instances of one generic item by their suffix, then in full. None of it + /// depends on the order translation reaches them in. + pub fn key(&self) -> (u32, &str, &str, &str) { + (self.order, &self.base, &self.suffix, &self.instance) + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SymKind { Class, @@ -85,8 +97,16 @@ impl Program { self.fields.len() - 1 } - /// Name every symbol and field, resolving collisions within each scope. + /// Put every item and method in order, and name every symbol and field, resolving + /// collisions within each scope in that order. pub fn name(&mut self) { + let syms = &self.syms; + self.items + .sort_by(|a, b| syms[item_sym(a)].key().cmp(&syms[item_sym(b)].key())); + for methods in self.methods.values_mut() { + methods.sort_by(|a, b| syms[a.sym].key().cmp(&syms[b.sym].key())); + } + let mut scopes: BTreeMap> = BTreeMap::new(); for (id, sym) in self.syms.iter().enumerate() { let scope = match sym.owner { @@ -100,10 +120,7 @@ impl Program { } for (scope, mut ids) in scopes { - ids.sort_by(|&a, &b| { - let (a, b) = (&self.syms[a], &self.syms[b]); - (a.order, &a.base, &a.suffix).cmp(&(b.order, &b.base, &b.suffix)) - }); + ids.sort_by(|&a, &b| self.syms[a].key().cmp(&self.syms[b].key())); let mut taken = HashSet::new(); match &scope { // The runtime's import binding. @@ -162,9 +179,6 @@ impl Program { if modules.keys().any(|module| module.as_slice() == ["rt"]) { return Err("a top-level module named `rt` would replace the runtime, rt.ts".into()); } - for items in modules.values_mut() { - items.sort_by_key(|item| self.syms[item_sym(item)].order); - } write_file(&out.join("rt.ts"), &format!("{HEADER}\n{RUNTIME}"))?; for (module, items) in modules { diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index 357c0e142..763b79aa1 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -20,11 +20,18 @@ fn cargo() -> Command { Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) } -/// Run the driver on a fixture with `args`, in its own build directory per `build`. -fn driver(name: &str, args: &[&std::ffi::OsStr], build: &str) -> Output { +fn fixture(name: &str) -> PathBuf { + manifest_dir().join("fixtures").join(name) +} + +/// Run the driver on a fixture with `config` and `args`, in its own build directory per +/// `build`. +fn driver(name: &str, config: &Path, args: &[&std::ffi::OsStr], build: &str) -> Output { Command::new(env!("CARGO_BIN_EXE_rust2-ts")) .arg("--config") - .arg(manifest_dir().join("fixtures").join(name).join("ts.toml")) + .arg(config) + .arg("--manifest-path") + .arg(fixture(name).join("Cargo.toml")) .args(args) .env("CARGO_TARGET_DIR", scratch().join(build)) .output() @@ -34,7 +41,8 @@ fn driver(name: &str, args: &[&std::ffi::OsStr], build: &str) -> Output { /// Run the driver on a fixture, returning its output directory and what it printed. fn translate(name: &str) -> (PathBuf, Output) { let out = scratch().join(name).join("out"); - let output = driver(name, &["--out".as_ref(), out.as_ref()], "build"); + let config = fixture(name).join("ts.toml"); + let output = driver(name, &config, &["--out".as_ref(), out.as_ref()], "build"); (out, output) } @@ -76,7 +84,7 @@ fn sources(dir: &Path) -> Vec<(PathBuf, String)> { /// Compare the output with the fixture's `expected/` directory. fn snapshot(name: &str, out: &Path) { - let expected = manifest_dir().join("fixtures").join(name).join("expected"); + let expected = fixture(name).join("expected"); let got = sources(out); if std::env::var_os("UPDATE_EXPECT").is_some() { let _ = std::fs::remove_dir_all(&expected); @@ -188,6 +196,59 @@ fn codec() { differential("codec-fixture", &out, "harness.ts", 20_000); } +/// Adding a root changes only the output of what it reaches: everything else keeps its +/// text and order, though translation reaches it in another order. +#[test] +fn source_order() { + let config = std::fs::read_to_string(fixture("codec").join("ts.toml")).unwrap(); + let roots = r#"roots = ["harness::run", "bench::run"]"#; + assert!(config.contains(roots), "codec's roots changed: update this test"); + let dir = scratch().join("codec").join("order"); + std::fs::create_dir_all(&dir).unwrap(); + let run = |name: &str, with: &str| { + let path = dir.join(format!("{name}.toml")); + std::fs::write(&path, config.replace(roots, with)).unwrap(); + let out = dir.join(name); + let output = driver("codec", &path, &["--out".as_ref(), out.as_ref()], "order"); + assert!( + output.status.success(), + "translating codec with {with} failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + sources(&out) + }; + let base = run("base", r#"roots = ["harness::run"]"#); + // First, so that translation reaches what both share in another order. + let added = run("added", r#"roots = ["bench::run", "harness::run"]"#); + for (rel, text) in &base { + let more = added.iter().find(|(r, _)| r == rel).map(|(_, text)| text); + let more = more.unwrap_or_else(|| panic!("{} is gone once bench::run is added", rel.display())); + let mut rest = lines(more).into_iter(); + for line in lines(text) { + assert!( + rest.any(|l| l == line), + "{}: this line changed or moved once bench::run was added:\n{line}", + rel.display() + ); + } + } +} + +/// A file's lines, with a line per imported name, so that importing one more name +/// changes no other line. +fn lines(text: &str) -> Vec { + let mut lines = Vec::new(); + for line in text.lines() { + match line.strip_prefix("import { ").and_then(|l| l.split_once(" } from ")) { + Some((names, from)) => { + lines.extend(names.split(", ").map(|name| format!("import {{ {name} }} from {from}"))) + } + None => lines.push(line.to_string()), + } + } + lines +} + #[test] fn lang() { let out = translated("lang"); @@ -217,7 +278,7 @@ fn reject() { got.push('\n'); } } - let path = manifest_dir().join("fixtures").join("reject").join("expected.txt"); + let path = fixture("reject").join("expected.txt"); if std::env::var_os("UPDATE_EXPECT").is_some() { std::fs::write(&path, &got).unwrap(); return; @@ -235,14 +296,15 @@ fn reject() { #[test] fn census() { let census = scratch().join("reject").join("census.md"); - let output = driver("reject", &["--census".as_ref(), census.as_ref()], "census"); + let config = fixture("reject").join("ts.toml"); + let output = driver("reject", &config, &["--census".as_ref(), census.as_ref()], "census"); assert!( output.status.success(), "the census of reject failed:\n{}", String::from_utf8_lossy(&output.stderr) ); let got = std::fs::read_to_string(&census).unwrap(); - let path = manifest_dir().join("fixtures").join("reject").join("census.md"); + let path = fixture("reject").join("census.md"); if std::env::var_os("UPDATE_EXPECT").is_some() { std::fs::write(&path, &got).unwrap(); return; From 270850028b24d2a9303f2fc6d45918268cf4276c Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 05:44:39 -0700 Subject: [PATCH 3/3] test(ts): regenerate snapshots in source order Only order changes: every file keeps the same lines. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/codec/expected/bench.ts | 6 +- ts/fixtures/codec/expected/coding/decode.ts | 114 +++++----- ts/fixtures/codec/expected/coding/encode.ts | 32 +-- ts/fixtures/codec/expected/coding/varint.ts | 8 +- ts/fixtures/codec/expected/coding/version.ts | 66 +++--- ts/fixtures/codec/expected/harness.ts | 8 +- ts/fixtures/codec/expected/lite/group.ts | 86 ++++---- ts/fixtures/codec/expected/lite/message.ts | 2 +- ts/fixtures/codec/expected/lite/probe.ts | 52 ++--- ts/fixtures/codec/expected/lite/version.ts | 18 +- ts/fixtures/lang/expected/fmt.ts | 50 ++--- ts/fixtures/lang/expected/generics.ts | 214 +++++++++---------- ts/fixtures/lang/expected/harness.ts | 2 +- ts/fixtures/lang/expected/shapes.ts | 70 +++--- 14 files changed, 364 insertions(+), 364 deletions(-) diff --git a/ts/fixtures/codec/expected/bench.ts b/ts/fixtures/codec/expected/bench.ts index 38e047b2f..b5c719b80 100644 --- a/ts/fixtures/codec/expected/bench.ts +++ b/ts/fixtures/codec/expected/bench.ts @@ -1,10 +1,10 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { Decoder, type DecodeError } from "./coding/decode.ts"; -import { Encoder, type EncodeError } from "./coding/encode.ts"; +import { type DecodeError, Decoder } from "./coding/decode.ts"; +import { type EncodeError, Encoder } from "./coding/encode.ts"; import { Form, zigzag, unzigzag } from "./coding/varint.ts"; -import { form, liteVersion, putUsize, takeU64, putU64, encodeError, decodeError } from "./harness.ts"; +import { form, liteVersion, putU64, putUsize, takeU64, decodeError, encodeError } from "./harness.ts"; import { Group } from "./lite/group.ts"; import { type Version } from "./lite/version.ts"; diff --git a/ts/fixtures/codec/expected/coding/decode.ts b/ts/fixtures/codec/expected/coding/decode.ts index 1bc86e3ef..0102bc9d6 100644 --- a/ts/fixtures/codec/expected/coding/decode.ts +++ b/ts/fixtures/codec/expected/coding/decode.ts @@ -2,7 +2,7 @@ import * as rt from "../rt.ts"; import { SessionError } from "../lib.ts"; -import { type Form, type BoundsExceeded, read } from "../coding/varint.ts"; +import { type BoundsExceeded, type Form, read } from "../coding/varint.ts"; import { type Control } from "../stats.ts"; /** A decode error. */ @@ -28,10 +28,6 @@ export type DecodeError = | { tag: "MultipleAuthTokens" }; export const DecodeError = { - from$BoundsExceeded(_: BoundsExceeded): DecodeError { - return { tag: "BoundsExceeded" }; - }, - fmt$Display(self: DecodeError, __formatter: rt.Formatter): rt.Result { if (self.tag === "Short") { return __formatter.writeStr("short buffer"); @@ -83,6 +79,10 @@ export const DecodeError = { } }, + from$FromUtf8Error(source: rt.FromUtf8Error): DecodeError { + return { tag: "InvalidString", _0: source }; + }, + fmt$Debug(self: DecodeError, f: rt.Formatter): rt.Result { if (self.tag === "Short") { return f.writeStr("Short"); @@ -130,10 +130,6 @@ export const DecodeError = { } }, - from$FromUtf8Error(source: rt.FromUtf8Error): DecodeError { - return { tag: "InvalidString", _0: source }; - }, - /** A complete frame cannot be extended by reading more stream bytes. */ complete(self: DecodeError): DecodeError { if (self.tag === "Short") { @@ -143,6 +139,10 @@ export const DecodeError = { return other; } }, + + from$BoundsExceeded(_: BoundsExceeded): DecodeError { + return { tag: "BoundsExceeded" }; + }, }; /** @@ -189,6 +189,13 @@ export class Decoder { return this._need; } + /** Record that a read wanted `more` bytes past the current position. */ + short(more: number): DecodeError { + const need = rt.usize.saturatingAdd(rt.usize.sub(this.len, this.buf.length), more); + this._need = rt.max(this._need, need); + return { tag: "Short" }; + } + /** The number of unread bytes. */ remaining(): number { return this.buf.length; @@ -199,20 +206,32 @@ export class Decoder { return this.buf.length === 0; } - /** Read a varint. */ - varint(): rt.Result { - const read_ = read(this.buf, this.form); - if (read_.ok) { - const value = read_.value[0]; - const rest = read_.value[1]; - this.buf = rest; - return rt.Ok(value); - } else if (!read_.ok && read_.error.tag === "Short") { - return rt.Err(this.short(rt.usize.add(this.buf.length, 1))); - } else { - const err = read_.error; - return rt.Err(err); + /** Read `len` raw bytes. */ + slice(len: number): rt.Result { + const splitAtChecked = rt.slice.splitAtChecked(this.buf, len); + if (splitAtChecked === undefined) { + return rt.Err(this.short(len)); + } + const head = splitAtChecked[0]; + const rest = splitAtChecked[1]; + this.buf = rest; + return rt.Ok(head); + } + + /** Read every remaining byte. */ + rest(): Uint8Array { + const taken = this.buf; + this.buf = new Uint8Array(0); + return taken; + } + + /** Split off the next `len` bytes as their own decoder, e.g. a size-prefixed body. */ + sub(len: number): rt.Result { + const slice = this.slice(len); + if (!slice.ok) { + return rt.Err(slice.error); } + return rt.Ok(Decoder.new(slice.value, this.form)); } /** Read a single byte. */ @@ -249,6 +268,22 @@ export class Decoder { } } + /** Read a varint. */ + varint(): rt.Result { + const read_ = read(this.buf, this.form); + if (read_.ok) { + const value = read_.value[0]; + const rest = read_.value[1]; + this.buf = rest; + return rt.Ok(value); + } else if (!read_.ok && read_.error.tag === "Short") { + return rt.Err(this.short(rt.usize.add(this.buf.length, 1))); + } else { + const err = read_.error; + return rt.Err(err); + } + } + /** Read an optional varint: 0 is `None`, and `n + 1` is `Some(n)`. */ varintOpt(): rt.Result { const varint = this.varint(); @@ -289,41 +324,6 @@ export class Decoder { } return rt.Ok(fromUtf8.value); } - - /** Read `len` raw bytes. */ - slice(len: number): rt.Result { - const splitAtChecked = rt.slice.splitAtChecked(this.buf, len); - if (splitAtChecked === undefined) { - return rt.Err(this.short(len)); - } - const head = splitAtChecked[0]; - const rest = splitAtChecked[1]; - this.buf = rest; - return rt.Ok(head); - } - - /** Split off the next `len` bytes as their own decoder, e.g. a size-prefixed body. */ - sub(len: number): rt.Result { - const slice = this.slice(len); - if (!slice.ok) { - return rt.Err(slice.error); - } - return rt.Ok(Decoder.new(slice.value, this.form)); - } - - /** Read every remaining byte. */ - rest(): Uint8Array { - const taken = this.buf; - this.buf = new Uint8Array(0); - return taken; - } - - /** Record that a read wanted `more` bytes past the current position. */ - short(more: number): DecodeError { - const need = rt.usize.saturatingAdd(rt.usize.sub(this.len, this.buf.length), more); - this._need = rt.max(this._need, need); - return { tag: "Short" }; - } } //# sourceMappingURL=decode.ts.map diff --git a/ts/fixtures/codec/expected/coding/encode.ts b/ts/fixtures/codec/expected/coding/encode.ts index 4ede16b1e..cee77a5c1 100644 --- a/ts/fixtures/codec/expected/coding/encode.ts +++ b/ts/fixtures/codec/expected/coding/encode.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; -import { type Form, type BoundsExceeded, write } from "../coding/varint.ts"; +import { type BoundsExceeded, type Form, write } from "../coding/varint.ts"; import { type Control } from "../stats.ts"; /** An error that occurs during encoding. */ @@ -15,10 +15,6 @@ export type EncodeError = | "Unsupported"; export const EncodeError = { - from(_: BoundsExceeded): EncodeError { - return "BoundsExceeded"; - }, - fmt$Display(self: EncodeError, __formatter: rt.Formatter): rt.Result { if (self === "BoundsExceeded") { return __formatter.writeStr("bounds exceeded"); @@ -40,6 +36,10 @@ export const EncodeError = { fmt$Debug(self: EncodeError, f: rt.Formatter): rt.Result { return f.writeStr(self === "BoundsExceeded" ? "BoundsExceeded" : self === "TooLarge" ? "TooLarge" : self === "Short" ? "Short" : self === "InvalidState" ? "InvalidState" : self === "TooMany" ? "TooMany" : self === "Version" ? "Version" : "Unsupported"); }, + + from(_: BoundsExceeded): EncodeError { + return "BoundsExceeded"; + }, }; /** @@ -63,6 +63,11 @@ export class Encoder { return new Encoder({ buf, form, control: undefined }); } + /** Write raw bytes. */ + slice(v: Uint8Array): void { + this.buf.extendFromSlice(v); + } + /** Write a single byte. */ u8(v: number): void { this.buf.push(v); @@ -139,6 +144,12 @@ export class Encoder { return rt.usize.sub(this.buf.length, prefix.body); } + /** Drop a reserved prefix and everything written since, as if neither was written. */ + discard(prefix: Prefix): void { + const start = prefix.kind === "Varint" ? rt.usize.sub(prefix.body, 1) : rt.usize.sub(prefix.body, 2); + this.buf.truncate(start); + } + /** Size a reserved prefix to everything written since. */ fill(prefix: Prefix): rt.Result { const body = prefix.body; @@ -174,17 +185,6 @@ export class Encoder { } return rt.Ok(undefined); } - - /** Drop a reserved prefix and everything written since, as if neither was written. */ - discard(prefix: Prefix): void { - const start = prefix.kind === "Varint" ? rt.usize.sub(prefix.body, 1) : rt.usize.sub(prefix.body, 2); - this.buf.truncate(start); - } - - /** Write raw bytes. */ - slice(v: Uint8Array): void { - this.buf.extendFromSlice(v); - } } /** A size prefix reserved ahead of a body, sized by [`Encoder::fill`] once it is written. */ diff --git a/ts/fixtures/codec/expected/coding/varint.ts b/ts/fixtures/codec/expected/coding/varint.ts index 5aee013c7..6778f4b97 100644 --- a/ts/fixtures/codec/expected/coding/varint.ts +++ b/ts/fixtures/codec/expected/coding/varint.ts @@ -7,13 +7,13 @@ import { type Version } from "../lite/version.ts"; /** The number does not fit the target: a varint wire form or a narrower integer. */ export class BoundsExceeded { - fmt$Display(__formatter: rt.Formatter): rt.Result { - return __formatter.writeStr("value out of range"); - } - fmt$Debug(f: rt.Formatter): rt.Result { return f.writeStr("BoundsExceeded"); } + + fmt$Display(__formatter: rt.Formatter): rt.Result { + return __formatter.writeStr("value out of range"); + } } /** How a protocol version lays out a varint on the wire. */ diff --git a/ts/fixtures/codec/expected/coding/version.ts b/ts/fixtures/codec/expected/coding/version.ts index f6d97a525..3d9826d3f 100644 --- a/ts/fixtures/codec/expected/coding/version.ts +++ b/ts/fixtures/codec/expected/coding/version.ts @@ -1,8 +1,8 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; -import { Decoder, type DecodeError } from "../coding/decode.ts"; -import { type Encoder, type EncodeError } from "../coding/encode.ts"; +import { type DecodeError, Decoder } from "../coding/decode.ts"; +import { type EncodeError, type Encoder } from "../coding/encode.ts"; import { type Form } from "../coding/varint.ts"; import { type Version as version_Version } from "../lite/version.ts"; @@ -14,17 +14,17 @@ export class Version { this._0 = _0; } - /** Encode the value to the given encoder, which may hold partial output on error. */ - encode$Form(w: Encoder, _: Form): rt.Result { - const varint = w.varint(this._0); + /** Decode the version number. */ + static decode(r: Decoder, _: Form): rt.Result { + const varint = r.varint(); if (!varint.ok) { return rt.Err(varint.error); } - return rt.Ok(undefined); + return rt.Ok(new Version(varint.value)); } /** Encode the value to the given encoder, which may hold partial output on error. */ - encode$Version(w: Encoder, _: version_Version): rt.Result { + encode$Form(w: Encoder, _: Form): rt.Result { const varint = w.varint(this._0); if (!varint.ok) { return rt.Err(varint.error); @@ -32,13 +32,13 @@ export class Version { return rt.Ok(undefined); } - /** Decode the version number. */ - static decode(r: Decoder, _: Form): rt.Result { - const varint = r.varint(); + /** Encode the value to the given encoder, which may hold partial output on error. */ + encode$Version(w: Encoder, _: version_Version): rt.Result { + const varint = w.varint(this._0); if (!varint.ok) { return rt.Err(varint.error); } - return rt.Ok(new Version(varint.value)); + return rt.Ok(undefined); } } @@ -61,6 +61,26 @@ export class Versions { return rt.Ok([value, rt.usize.sub(buf.length, r.remaining())]); } + /** Decode the version list. */ + static decode(r: Decoder, version: Form): rt.Result { + const varint = r.varint(); + if (!varint.ok) { + return rt.Err(varint.error); + } + const count = varint.value; + let vs: Version[] = []; + const end = count; + for (let _ = 0n; _ < end; _++) { + const decode = Version.decode(r, version); + if (!decode.ok) { + return rt.Err(decode.error); + } + const v = decode.value; + vs.push(rt.copy(v)); + } + return rt.Ok(new Versions(vs)); + } + /** Encode the version list. */ encode$Form(w: Encoder, version: Form): rt.Result { const varint = w.varint(BigInt(this._0.length)); @@ -76,10 +96,6 @@ export class Versions { return rt.Ok(undefined); } - static from(vs: Version[]): Versions { - return new Versions(rt.slice.toVec(vs)); - } - /** Encode the version list. */ encode$Version(w: Encoder, version: version_Version): rt.Result { const varint = w.varint(BigInt(this._0.length)); @@ -95,24 +111,8 @@ export class Versions { return rt.Ok(undefined); } - /** Decode the version list. */ - static decode(r: Decoder, version: Form): rt.Result { - const varint = r.varint(); - if (!varint.ok) { - return rt.Err(varint.error); - } - const count = varint.value; - let vs: Version[] = []; - const end = count; - for (let _ = 0n; _ < end; _++) { - const decode = Version.decode(r, version); - if (!decode.ok) { - return rt.Err(decode.error); - } - const v = decode.value; - vs.push(rt.copy(v)); - } - return rt.Ok(new Versions(vs)); + static from(vs: Version[]): Versions { + return new Versions(rt.slice.toVec(vs)); } } diff --git a/ts/fixtures/codec/expected/harness.ts b/ts/fixtures/codec/expected/harness.ts index dd5bc9af3..6ea9cf419 100644 --- a/ts/fixtures/codec/expected/harness.ts +++ b/ts/fixtures/codec/expected/harness.ts @@ -2,10 +2,10 @@ import * as rt from "./rt.ts"; import { type SessionError } from "./lib.ts"; -import { Decoder, DecodeError } from "./coding/decode.ts"; -import { Encoder, type Prefix, EncodeError } from "./coding/encode.ts"; -import { Form, zigzag as varint_zigzag, unzigzag, size, BoundsExceeded } from "./coding/varint.ts"; -import { Versions, Version } from "./coding/version.ts"; +import { DecodeError, Decoder } from "./coding/decode.ts"; +import { EncodeError, Encoder, type Prefix } from "./coding/encode.ts"; +import { BoundsExceeded, Form, size, zigzag as varint_zigzag, unzigzag } from "./coding/varint.ts"; +import { Version, Versions } from "./coding/version.ts"; import { Group } from "./lite/group.ts"; import { Probe } from "./lite/probe.ts"; import { type Version as version_Version } from "./lite/version.ts"; diff --git a/ts/fixtures/codec/expected/lite/group.ts b/ts/fixtures/codec/expected/lite/group.ts index d2ff70230..a4b33a2dc 100644 --- a/ts/fixtures/codec/expected/lite/group.ts +++ b/ts/fixtures/codec/expected/lite/group.ts @@ -1,8 +1,8 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; -import { Decoder, type DecodeError } from "../coding/decode.ts"; -import { type Encoder, type EncodeError } from "../coding/encode.ts"; +import { type DecodeError, Decoder } from "../coding/decode.ts"; +import { type EncodeError, type Encoder } from "../coding/encode.ts"; import { Form } from "../coding/varint.ts"; import { decodeWith$Group } from "../lite/message.ts"; import { Version } from "../lite/version.ts"; @@ -29,30 +29,29 @@ export class Group { return rt.Ok([value, rt.usize.sub(buf.length, r.remaining())]); } - /** Encode the value to the given encoder, which may hold partial output on error. */ - encode(w: Encoder, version: Version): rt.Result { - const prefix = w.prefixVarint(); - const encodeMsg = this.encodeMsg(w, version); - if (!encodeMsg.ok) { - return rt.Err(encodeMsg.error); + /** Decode a message body (without size prefix). */ + static decodeMsg(r: Decoder, version: Version): rt.Result { + const varint = r.varint(); + if (!varint.ok) { + return rt.Err(varint.error); } - if (w.since(prefix) > 65535) { - w.discard(prefix); - return rt.Err("TooLarge"); + const subscribe = varint.value; + const varint2 = r.varint(); + if (!varint2.ok) { + return rt.Err(varint2.error); } - const fill = w.fill(prefix); - if (!fill.ok) { - return rt.Err(fill.error); + const sequence = varint2.value; + let frameStart: bigint; + if (Version.hasFrameBounds(version)) { + const varint3 = r.varint(); + if (!varint3.ok) { + return rt.Err(varint3.error); + } + frameStart = varint3.value; + } else { + frameStart = 0n; } - w.control = undefined; - return rt.Ok(undefined); - } - - /** Decode the value from the front of the decoder. */ - static decode(r: Decoder, version: Version): rt.Result { - return decodeWith$Group(r, (body: Decoder): rt.Result => { - return Group.decodeMsg(body, version); - }); + return rt.Ok(new Group({ subscribe, sequence, frameStart })); } /** Encode this message body (without size prefix). */ @@ -76,29 +75,30 @@ export class Group { return rt.Ok(undefined); } - /** Decode a message body (without size prefix). */ - static decodeMsg(r: Decoder, version: Version): rt.Result { - const varint = r.varint(); - if (!varint.ok) { - return rt.Err(varint.error); + /** Encode the value to the given encoder, which may hold partial output on error. */ + encode(w: Encoder, version: Version): rt.Result { + const prefix = w.prefixVarint(); + const encodeMsg = this.encodeMsg(w, version); + if (!encodeMsg.ok) { + return rt.Err(encodeMsg.error); } - const subscribe = varint.value; - const varint2 = r.varint(); - if (!varint2.ok) { - return rt.Err(varint2.error); + if (w.since(prefix) > 65535) { + w.discard(prefix); + return rt.Err("TooLarge"); } - const sequence = varint2.value; - let frameStart: bigint; - if (Version.hasFrameBounds(version)) { - const varint3 = r.varint(); - if (!varint3.ok) { - return rt.Err(varint3.error); - } - frameStart = varint3.value; - } else { - frameStart = 0n; + const fill = w.fill(prefix); + if (!fill.ok) { + return rt.Err(fill.error); } - return rt.Ok(new Group({ subscribe, sequence, frameStart })); + w.control = undefined; + return rt.Ok(undefined); + } + + /** Decode the value from the front of the decoder. */ + static decode(r: Decoder, version: Version): rt.Result { + return decodeWith$Group(r, (body: Decoder): rt.Result => { + return Group.decodeMsg(body, version); + }); } } diff --git a/ts/fixtures/codec/expected/lite/message.ts b/ts/fixtures/codec/expected/lite/message.ts index 12188e15a..7e334bc3b 100644 --- a/ts/fixtures/codec/expected/lite/message.ts +++ b/ts/fixtures/codec/expected/lite/message.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; -import { type Decoder, DecodeError } from "../coding/decode.ts"; +import { DecodeError, type Decoder } from "../coding/decode.ts"; import { type Group } from "../lite/group.ts"; import { type Probe } from "../lite/probe.ts"; import { type Control } from "../stats.ts"; diff --git a/ts/fixtures/codec/expected/lite/probe.ts b/ts/fixtures/codec/expected/lite/probe.ts index ab520683e..561ee210e 100644 --- a/ts/fixtures/codec/expected/lite/probe.ts +++ b/ts/fixtures/codec/expected/lite/probe.ts @@ -1,8 +1,8 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; -import { Decoder, type DecodeError } from "../coding/decode.ts"; -import { type Encoder, type EncodeError } from "../coding/encode.ts"; +import { type DecodeError, Decoder } from "../coding/decode.ts"; +import { type EncodeError, type Encoder } from "../coding/encode.ts"; import { Form } from "../coding/varint.ts"; import { decodeWith$Probe } from "../lite/message.ts"; import { Version } from "../lite/version.ts"; @@ -60,30 +60,6 @@ export class Probe { }); } - /** Encode this message body (without size prefix). */ - encodeMsg(w: Encoder, version: Version): rt.Result { - if (version === "Lite01" || version === "Lite02") { - return rt.Err("Version"); - } - const wire = rt.option.unwrapOr(rt.option.map(this.bitrate, (v: bigint): bigint => { - return rt.max(v, 1n); - }), 0n); - const varint = w.varint(wire); - if (!varint.ok) { - return rt.Err(varint.error); - } - if (Version.hasProbeRtt(version)) { - const wire2 = rt.option.unwrapOr(rt.option.map(this.rtt, (v2: bigint): bigint => { - return rt.max(v2, 1n); - }), 0n); - const varint2 = w.varint(wire2); - if (!varint2.ok) { - return rt.Err(varint2.error); - } - } - return rt.Ok(undefined); - } - /** Decode a message body (without size prefix). */ static decodeMsg(r: Decoder, version: Version): rt.Result { if (version === "Lite01" || version === "Lite02") { @@ -117,6 +93,30 @@ export class Probe { } return rt.Ok(new Probe({ bitrate, rtt })); } + + /** Encode this message body (without size prefix). */ + encodeMsg(w: Encoder, version: Version): rt.Result { + if (version === "Lite01" || version === "Lite02") { + return rt.Err("Version"); + } + const wire = rt.option.unwrapOr(rt.option.map(this.bitrate, (v: bigint): bigint => { + return rt.max(v, 1n); + }), 0n); + const varint = w.varint(wire); + if (!varint.ok) { + return rt.Err(varint.error); + } + if (Version.hasProbeRtt(version)) { + const wire2 = rt.option.unwrapOr(rt.option.map(this.rtt, (v2: bigint): bigint => { + return rt.max(v2, 1n); + }), 0n); + const varint2 = w.varint(wire2); + if (!varint2.ok) { + return rt.Err(varint2.error); + } + } + return rt.Ok(undefined); + } } //# sourceMappingURL=probe.ts.map diff --git a/ts/fixtures/codec/expected/lite/version.ts b/ts/fixtures/codec/expected/lite/version.ts index 7cb02e404..f1238b5a8 100644 --- a/ts/fixtures/codec/expected/lite/version.ts +++ b/ts/fixtures/codec/expected/lite/version.ts @@ -4,6 +4,15 @@ export type Version = "Lite01" | "Lite02" | "Lite03" | "Lite04" | "Lite05" | "Lite06" | "Lite07"; export const Version = { + /** + * Whether the PROBE message carries the RTT field. Added in lite-04; lite-03 + * carries the bitrate alone, so a report with only an RTT to give says nothing + * there and must not be sent. + */ + hasProbeRtt(self: Version): boolean { + return !(self === "Lite01" || self === "Lite02" || self === "Lite03"); + }, + /** * Whether SUBSCRIBE, SUBSCRIBE_UPDATE, FETCH, and GROUP carry frame indices * alongside their group sequences, so a subscription or fetch can start and end @@ -15,15 +24,6 @@ export const Version = { hasFrameBounds(self: Version): boolean { return !(self === "Lite01" || self === "Lite02" || self === "Lite03" || self === "Lite04" || self === "Lite05"); }, - - /** - * Whether the PROBE message carries the RTT field. Added in lite-04; lite-03 - * carries the bitrate alone, so a report with only an RTT to give says nothing - * there and must not be sent. - */ - hasProbeRtt(self: Version): boolean { - return !(self === "Lite01" || self === "Lite02" || self === "Lite03"); - }, }; //# sourceMappingURL=version.ts.map diff --git a/ts/fixtures/lang/expected/fmt.ts b/ts/fixtures/lang/expected/fmt.ts index f55dbccd6..ac9ba7611 100644 --- a/ts/fixtures/lang/expected/fmt.ts +++ b/ts/fixtures/lang/expected/fmt.ts @@ -628,20 +628,19 @@ export type Fault = | { tag: "At"; _0: Pair }; export const Fault = { - /** The fault `data` picks. */ - new(data: Uint8Array): Fault { - const at = (i: number): number => { - return rt.option.unwrapOr(rt.slice.get(data, i), 0); - }; - const value = rt.u8.rem(at(0), 4); - if (value === 0) { - return { tag: "Short" }; - } else if (value === 1) { - return { tag: "Code", _0: (at(1) << 8) | at(2) }; - } else if (value === 2) { - return { tag: "TooLarge", size: (((at(1) << 24) >>> 0) | at(2)) >>> 0, max: at(3) }; + fmt$Debug(self: Fault, f: rt.Formatter): rt.Result { + if (self.tag === "Short") { + return f.writeStr("Short"); + } else if (self.tag === "Code") { + const __self0 = self._0; + return f.debugTuple("Code").field((f: rt.Formatter) => rt.u16.display(__self0, f)).finish(); + } else if (self.tag === "TooLarge") { + const __self02 = self.size; + const __self1 = self.max; + return f.debugStruct("TooLarge").field("size", (f: rt.Formatter) => rt.usize.display(__self02, f)).field("max", (f: rt.Formatter) => rt.usize.display(__self1, f)).finish(); } else { - return { tag: "At", _0: new Pair(at(1), BigInt.asIntN(64, BigInt((at(2) << 24) >> 24) << 40n)) }; + const __self03 = self._0; + return f.debugTuple("At").field((f: rt.Formatter) => __self03.fmt(f)).finish(); } }, @@ -661,19 +660,20 @@ export const Fault = { } }, - fmt$Debug(self: Fault, f: rt.Formatter): rt.Result { - if (self.tag === "Short") { - return f.writeStr("Short"); - } else if (self.tag === "Code") { - const __self0 = self._0; - return f.debugTuple("Code").field((f: rt.Formatter) => rt.u16.display(__self0, f)).finish(); - } else if (self.tag === "TooLarge") { - const __self02 = self.size; - const __self1 = self.max; - return f.debugStruct("TooLarge").field("size", (f: rt.Formatter) => rt.usize.display(__self02, f)).field("max", (f: rt.Formatter) => rt.usize.display(__self1, f)).finish(); + /** The fault `data` picks. */ + new(data: Uint8Array): Fault { + const at = (i: number): number => { + return rt.option.unwrapOr(rt.slice.get(data, i), 0); + }; + const value = rt.u8.rem(at(0), 4); + if (value === 0) { + return { tag: "Short" }; + } else if (value === 1) { + return { tag: "Code", _0: (at(1) << 8) | at(2) }; + } else if (value === 2) { + return { tag: "TooLarge", size: (((at(1) << 24) >>> 0) | at(2)) >>> 0, max: at(3) }; } else { - const __self03 = self._0; - return f.debugTuple("At").field((f: rt.Formatter) => __self03.fmt(f)).finish(); + return { tag: "At", _0: new Pair(at(1), BigInt.asIntN(64, BigInt((at(2) << 24) >> 24) << 40n)) }; } }, }; diff --git a/ts/fixtures/lang/expected/generics.ts b/ts/fixtures/lang/expected/generics.ts index 7be0d9187..21c43c9da 100644 --- a/ts/fixtures/lang/expected/generics.ts +++ b/ts/fixtures/lang/expected/generics.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { Pair, put } from "./fmt.ts"; +import { put, Pair } from "./fmt.ts"; import { Point, Meters, Shape } from "./shapes.ts"; /** A generic struct, with methods on every instance, on some, and on one. */ @@ -14,103 +14,93 @@ export class Wrap { this.count = fields.count; } - static new$Point(value: Point): Wrap { - return new Wrap({ value: rt.copy(value), count: 0 }); - } - - bump$Point(this: Wrap): number { - this.count = rt.u8.wrappingAdd(this.count, 1); - return this.count; + fmt$Option_u8(this: Wrap, f: rt.Formatter): rt.Result { + return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => rt.fmt.option(this.value, f, rt.u8.display)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); } - static new$u8(value: number): Wrap { - return new Wrap({ value, count: 0 }); + fmt$Pair(this: Wrap, f: rt.Formatter): rt.Result { + return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => this.value.fmt(f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); } - bump$u8(this: Wrap): number { - this.count = rt.u8.wrappingAdd(this.count, 1); - return this.count; + fmt$Point(this: Wrap, f: rt.Formatter): rt.Result { + return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => this.value.fmt(f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); } - static new$Wrap_Pair(value: Wrap): Wrap> { - return new Wrap({ value: rt.copy(value), count: 0 }); + fmt$Result_u8_Shape(this: Wrap>, f: rt.Formatter): rt.Result { + return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => rt.fmt.result(this.value, f, rt.u8.display, (value: Shape, f: rt.Formatter) => Shape.fmt(value, f))).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); } - static new$Pair(value: Pair): Wrap { - return new Wrap({ value: rt.copy(value), count: 0 }); + fmt$Shape(this: Wrap, f: rt.Formatter): rt.Result { + return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => Shape.fmt(this.value, f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); } - static new$Shape(value: Shape): Wrap { - return new Wrap({ value, count: 0 }); + fmt$Vec_u16(this: Wrap, f: rt.Formatter): rt.Result { + return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => rt.fmt.list(this.value, f, rt.u16.display)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); } - intoInner(this: Wrap): Point { - return rt.copy(this.value); + fmt$Wrap_Pair(this: Wrap>, f: rt.Formatter): rt.Result { + return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => this.value.fmt$Pair(f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); } - fmt$Point(this: Wrap, f: rt.Formatter): rt.Result { - return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => this.value.fmt(f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); + fmt$i16(this: Wrap, f: rt.Formatter): rt.Result { + return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => rt.i16.display(this.value, f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); } fmt$u8(this: Wrap, f: rt.Formatter): rt.Result { return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => rt.u8.display(this.value, f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); } - fmt$Wrap_Pair(this: Wrap>, f: rt.Formatter): rt.Result { - return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => this.value.fmt$Pair(f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); + eq(this: Wrap, other: Wrap): boolean { + return this.count === other.count && this.value.eq(other.value); } - fmt$Shape(this: Wrap, f: rt.Formatter): rt.Result { - return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => Shape.fmt(this.value, f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); + static new$Option_u8(value: number | undefined): Wrap { + return new Wrap({ value, count: 0 }); } - double(this: Wrap): number { - return rt.u16.mul(this.value, 2); + static new$Pair(value: Pair): Wrap { + return new Wrap({ value: rt.copy(value), count: 0 }); } - get$u8(this: Wrap): number { - return this.value; + static new$Point(value: Point): Wrap { + return new Wrap({ value: rt.copy(value), count: 0 }); } - get$Pair(this: Wrap): Pair { - return this.value; + static new$Shape(value: Shape): Wrap { + return new Wrap({ value, count: 0 }); } - get$Wrap_Pair(this: Wrap>): Wrap { - return this.value; + static new$Wrap_Pair(value: Wrap): Wrap> { + return new Wrap({ value: rt.copy(value), count: 0 }); } - scaled$Meters(this: Wrap): bigint { - return rt.u64.saturatingAdd(this.value.area(), BigInt(this.count)); + static new$i16(value: number): Wrap { + return new Wrap({ value, count: 0 }); } - scaled$Shape(this: Wrap): bigint { - return rt.u64.saturatingAdd(Shape.area(this.value), BigInt(this.count)); + static new$u8(value: number): Wrap { + return new Wrap({ value, count: 0 }); } - /** A default method, monomorphized for each type. */ - describe$Meters(this: Wrap, out: rt.ByteVec): void { - out.push(0); - out.extendFromSlice(rt.u64.toBeBytes(this.area$Meters())); + get$Option_u8(this: Wrap): number | undefined { + return this.value; } - /** A default method, monomorphized for each type. */ - describe$Shape(this: Wrap, out: rt.ByteVec): void { - out.push(4); - out.extendFromSlice(rt.u64.toBeBytes(this.area$Shape())); + get$Pair(this: Wrap): Pair { + return this.value; } - /** A method with its own type parameter. */ - map(this: Wrap, f: (a0: number) => Pair): Wrap { - return new Wrap({ value: f(this.value), count: this.count }); + get$Wrap_Pair(this: Wrap>): Wrap { + return this.value; } - eq(this: Wrap, other: Wrap): boolean { - return this.count === other.count && this.value.eq(other.value); + get$u8(this: Wrap): number { + return this.value; } - fmt$Pair(this: Wrap, f: rt.Formatter): rt.Result { - return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => this.value.fmt(f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); + bump$Point(this: Wrap): number { + this.count = rt.u8.wrappingAdd(this.count, 1); + return this.count; } bump$Vec_u16(this: Wrap): number { @@ -118,32 +108,30 @@ export class Wrap { return this.count; } - static new$Option_u8(value: number | undefined): Wrap { - return new Wrap({ value, count: 0 }); - } - - get$Option_u8(this: Wrap): number | undefined { - return this.value; + bump$u8(this: Wrap): number { + this.count = rt.u8.wrappingAdd(this.count, 1); + return this.count; } - fmt$Vec_u16(this: Wrap, f: rt.Formatter): rt.Result { - return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => rt.fmt.list(this.value, f, rt.u16.display)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); + intoInner(this: Wrap): Point { + return rt.copy(this.value); } - fmt$Option_u8(this: Wrap, f: rt.Formatter): rt.Result { - return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => rt.fmt.option(this.value, f, rt.u8.display)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); + /** A method with its own type parameter. */ + map(this: Wrap, f: (a0: number) => Pair): Wrap { + return new Wrap({ value: f(this.value), count: this.count }); } - fmt$Result_u8_Shape(this: Wrap>, f: rt.Formatter): rt.Result { - return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => rt.fmt.result(this.value, f, rt.u8.display, (value: Shape, f: rt.Formatter) => Shape.fmt(value, f))).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); + scaled$Meters(this: Wrap): bigint { + return rt.u64.saturatingAdd(this.value.area(), BigInt(this.count)); } - static new$i16(value: number): Wrap { - return new Wrap({ value, count: 0 }); + scaled$Shape(this: Wrap): bigint { + return rt.u64.saturatingAdd(Shape.area(this.value), BigInt(this.count)); } - fmt$i16(this: Wrap, f: rt.Formatter): rt.Result { - return f.debugStruct("Wrap").field("value", (f: rt.Formatter) => rt.i16.display(this.value, f)).field("count", (f: rt.Formatter) => rt.u8.display(this.count, f)).finish(); + double(this: Wrap): number { + return rt.u16.mul(this.value, 2); } area$Meters(this: Wrap): bigint { @@ -153,39 +141,33 @@ export class Wrap { area$Shape(this: Wrap): bigint { return Shape.area(this.value); } + + /** A default method, monomorphized for each type. */ + describe$Meters(this: Wrap, out: rt.ByteVec): void { + out.push(0); + out.extendFromSlice(rt.u64.toBeBytes(this.area$Meters())); + } + + /** A default method, monomorphized for each type. */ + describe$Shape(this: Wrap, out: rt.ByteVec): void { + out.push(4); + out.extendFromSlice(rt.u64.toBeBytes(this.area$Shape())); + } } /** A generic enum, with a companion function per instance. */ export type Either = { tag: "Left"; _0: L } | { tag: "Right"; value: R } | { tag: "Neither" }; export const Either = { - flip(self: Either): Either { + fmt$Point_u8(self: Either, f: rt.Formatter): rt.Result { if (self.tag === "Left") { - const l = self._0; - return { tag: "Right", value: l }; + const __self0 = self._0; + return f.debugTuple("Left").field((f: rt.Formatter) => __self0.fmt(f)).finish(); } else if (self.tag === "Right") { - const value = rt.copy(self.value); - return { tag: "Left", _0: rt.copy(value) }; - } else { - return { tag: "Neither" }; - } - }, - - left$u8_Point(self: Either): number | undefined { - if (self.tag === "Left") { - const l = self._0; - return l; - } else { - return undefined; - } - }, - - left$Point_u8(self: Either): Point | undefined { - if (self.tag === "Left") { - const l = rt.copy(self._0); - return rt.copy(l); + const __self02 = self.value; + return f.debugStruct("Right").field("value", (f: rt.Formatter) => rt.u8.display(__self02, f)).finish(); } else { - return undefined; + return f.writeStr("Neither"); } }, @@ -201,18 +183,36 @@ export const Either = { } }, - fmt$Point_u8(self: Either, f: rt.Formatter): rt.Result { + fmt$u8_u16(self: Either, f: rt.Formatter): rt.Result { if (self.tag === "Left") { const __self0 = self._0; - return f.debugTuple("Left").field((f: rt.Formatter) => __self0.fmt(f)).finish(); + return f.debugTuple("Left").field((f: rt.Formatter) => rt.u8.display(__self0, f)).finish(); } else if (self.tag === "Right") { const __self02 = self.value; - return f.debugStruct("Right").field("value", (f: rt.Formatter) => rt.u8.display(__self02, f)).finish(); + return f.debugStruct("Right").field("value", (f: rt.Formatter) => rt.u16.display(__self02, f)).finish(); } else { return f.writeStr("Neither"); } }, + left$Point_u8(self: Either): Point | undefined { + if (self.tag === "Left") { + const l = rt.copy(self._0); + return rt.copy(l); + } else { + return undefined; + } + }, + + left$u8_Point(self: Either): number | undefined { + if (self.tag === "Left") { + const l = self._0; + return l; + } else { + return undefined; + } + }, + left$u8_u16(self: Either): number | undefined { if (self.tag === "Left") { const l = self._0; @@ -222,15 +222,15 @@ export const Either = { } }, - fmt$u8_u16(self: Either, f: rt.Formatter): rt.Result { + flip(self: Either): Either { if (self.tag === "Left") { - const __self0 = self._0; - return f.debugTuple("Left").field((f: rt.Formatter) => rt.u8.display(__self0, f)).finish(); + const l = self._0; + return { tag: "Right", value: l }; } else if (self.tag === "Right") { - const __self02 = self.value; - return f.debugStruct("Right").field("value", (f: rt.Formatter) => rt.u16.display(__self02, f)).finish(); + const value = rt.copy(self.value); + return { tag: "Left", _0: rt.copy(value) }; } else { - return f.writeStr("Neither"); + return { tag: "Neither" }; } }, }; @@ -247,13 +247,13 @@ export class Tagged { this.all = fields.all; } - first(this: Tagged, number>): Wrap | undefined { - return rt.copy(rt.slice.first(this.all)); - } - fmt(this: Tagged, number>, f: rt.Formatter): rt.Result { return f.debugStruct("Tagged").field("key", (f: rt.Formatter) => Either.fmt$u8_u16(this.key, f)).field("inner", (f: rt.Formatter) => this.inner.fmt$i16(f)).field("all", (f: rt.Formatter) => rt.fmt.list(this.all, f, (value: Wrap, f: rt.Formatter) => value.fmt$i16(f))).finish(); } + + first(this: Tagged, number>): Wrap | undefined { + return rt.copy(rt.slice.first(this.all)); + } } /** Each method once per instance: `Wrap` of a struct, an enum, a number, and itself. */ diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 047779418..2b41bcd2a 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -4,7 +4,7 @@ import * as rt from "./rt.ts"; import { ints, strings, derived, written, panics } from "./fmt.ts"; import { methods } from "./generics.ts"; import { u8Op, u16Op, u32Op, u64Op, u128Op, usizeOp, i8Op, i16Op, i32Op, i64Op, i128Op, isizeOp, i8Neg, i16Neg, i32Neg, i64Neg, i128Neg, isizeNeg, cast, convert } from "./ints.ts"; -import { copies, loops, patterns, closures, discriminants, library } from "./shapes.ts"; +import { copies, discriminants, loops, patterns, closures, library } from "./shapes.ts"; /** Run one case. */ export function run(input: Uint8Array): rt.ByteVec { diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 99ab7a303..8fe7cbc62 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -12,12 +12,16 @@ export class Point { this.y = fields.y; } - static new(x: number, y: number): Point { - return new Point({ x, y }); + fmt(f: rt.Formatter): rt.Result { + return f.debugStruct("Point").field("x", (f: rt.Formatter) => rt.i32.display(this.x, f)).field("y", (f: rt.Formatter) => rt.i32.display(this.y, f)).finish(); } - bump(): void { - this.y = rt.i32.add(this.y, 1); + eq(other: Point): boolean { + return this.x === other.x && this.y === other.y; + } + + static new(x: number, y: number): Point { + return new Point({ x, y }); } /** Changes `self`, which a caller's copy must not see. */ @@ -26,12 +30,8 @@ export class Point { return rt.copy(this); } - eq(other: Point): boolean { - return this.x === other.x && this.y === other.y; - } - - fmt(f: rt.Formatter): rt.Result { - return f.debugStruct("Point").field("x", (f: rt.Formatter) => rt.i32.display(this.x, f)).field("y", (f: rt.Formatter) => rt.i32.display(this.y, f)).finish(); + bump(): void { + this.y = rt.i32.add(this.y, 1); } } @@ -43,15 +43,15 @@ export class Meters { this._0 = _0; } + area(): bigint { + return this._0; + } + /** A default method, monomorphized for each type. */ describe(out: rt.ByteVec): void { out.push(0xaa); out.extendFromSlice(rt.u64.toBeBytes(this._0)); } - - area(): bigint { - return this._0; - } } /** An enum with data, and one without. */ @@ -61,6 +61,21 @@ export type Shape = | { tag: "Rect"; corner: Point; width: number; height: number }; export const Shape = { + fmt(self: Shape, f: rt.Formatter): rt.Result { + if (self.tag === "Dot") { + return f.writeStr("Dot"); + } else if (self.tag === "Line") { + const __self0 = self._0; + const __self1 = self._1; + return f.debugTuple("Line").field((f: rt.Formatter) => __self0.fmt(f)).field((f: rt.Formatter) => __self1.fmt(f)).finish(); + } else { + const __self02 = self.corner; + const __self12 = self.width; + const __self2 = self.height; + return f.debugStruct("Rect").field("corner", (f: rt.Formatter) => __self02.fmt(f)).field("width", (f: rt.Formatter) => rt.u16.display(__self12, f)).field("height", (f: rt.Formatter) => rt.u16.display(__self2, f)).finish(); + } + }, + /** A default method, monomorphized for each type. */ describe(self: Shape, out: rt.ByteVec): void { out.push(4); @@ -78,21 +93,6 @@ export const Shape = { return rt.u64.mul(BigInt(width), BigInt(height)); } }, - - fmt(self: Shape, f: rt.Formatter): rt.Result { - if (self.tag === "Dot") { - return f.writeStr("Dot"); - } else if (self.tag === "Line") { - const __self0 = self._0; - const __self1 = self._1; - return f.debugTuple("Line").field((f: rt.Formatter) => __self0.fmt(f)).field((f: rt.Formatter) => __self1.fmt(f)).finish(); - } else { - const __self02 = self.corner; - const __self12 = self.width; - const __self2 = self.height; - return f.debugStruct("Rect").field("corner", (f: rt.Formatter) => __self02.fmt(f)).field("width", (f: rt.Formatter) => rt.u16.display(__self12, f)).field("height", (f: rt.Formatter) => rt.u16.display(__self2, f)).finish(); - } - }, }; /** Discriminants a cast truncates, or reads with another sign. */ @@ -102,20 +102,20 @@ export type Signed = "Neg" | "Min" | "Pos"; export type Dir = "North" | "East" | "South" | "West"; -export function total$Shape(items: Shape[], out: rt.ByteVec): bigint { +export function total$Meters(items: Meters[], out: rt.ByteVec): bigint { let sum: bigint = 0n; for (const item of items) { - Shape.describe(item, out); - sum = rt.u64.saturatingAdd(sum, Shape.area(item)); + item.describe(out); + sum = rt.u64.saturatingAdd(sum, item.area()); } return sum; } -export function total$Meters(items: Meters[], out: rt.ByteVec): bigint { +export function total$Shape(items: Shape[], out: rt.ByteVec): bigint { let sum: bigint = 0n; for (const item of items) { - item.describe(out); - sum = rt.u64.saturatingAdd(sum, item.area()); + Shape.describe(item, out); + sum = rt.u64.saturatingAdd(sum, Shape.area(item)); } return sum; }