From 1f4bbdb1cd352dba20cab8735595c115d2bb0599 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:07:36 -0700 Subject: [PATCH 1/3] chore(quest): claim quest/m2/ts-generic-methods.md Quest-Claim: b477debdaead0d17 From 3f88086b8b7897bd6b3c61ea0d1a24b0ecffc841 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:19:04 -0700 Subject: [PATCH 2/3] feat(ts): type each generic class method's this as its instance Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/lang/expected/generics.ts | 312 ++++++++++++++++++++++++++ ts/fixtures/lang/expected/harness.ts | 7 +- ts/fixtures/lang/src/fmt.rs | 2 +- ts/fixtures/lang/src/generics.rs | 173 ++++++++++++++ ts/fixtures/lang/src/harness.rs | 7 +- ts/fixtures/lang/src/lib.rs | 1 + ts/src/lower/body.rs | 47 +++- ts/src/lower/mod.rs | 37 ++- 8 files changed, 562 insertions(+), 24 deletions(-) create mode 100644 ts/fixtures/lang/expected/generics.ts create mode 100644 ts/fixtures/lang/src/generics.rs diff --git a/ts/fixtures/lang/expected/generics.ts b/ts/fixtures/lang/expected/generics.ts new file mode 100644 index 000000000..3edada406 --- /dev/null +++ b/ts/fixtures/lang/expected/generics.ts @@ -0,0 +1,312 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.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. */ +export class Wrap { + value: T; + count: number; + + constructor(fields: { value: T; count: number }) { + this.value = fields.value; + 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; + } + + static new$u8(value: number): Wrap { + return new Wrap({ value, count: 0 }); + } + + bump$u8(this: Wrap): number { + this.count = rt.u8.wrappingAdd(this.count, 1); + return this.count; + } + + static new$Wrap_Pair(value: Wrap): Wrap> { + return new Wrap({ value: rt.copy(value), count: 0 }); + } + + static new$Pair(value: Pair): Wrap { + return new Wrap({ value: rt.copy(value), count: 0 }); + } + + static new$Shape(value: Shape): Wrap { + return new Wrap({ value, count: 0 }); + } + + intoInner(this: Wrap): Point { + return rt.copy(this.value); + } + + 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$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(); + } + + 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(); + } + + double(this: Wrap): number { + return rt.u16.mul(this.value, 2); + } + + get$u8(this: Wrap): number { + return this.value; + } + + get$Pair(this: Wrap): Pair { + return this.value; + } + + get$Wrap_Pair(this: Wrap>): Wrap { + return this.value; + } + + scaled$Meters(this: Wrap): bigint { + return rt.u64.saturatingAdd(this.value.area(), BigInt(this.count)); + } + + scaled$Shape(this: Wrap): bigint { + return rt.u64.saturatingAdd(Shape.area(this.value), BigInt(this.count)); + } + + /** 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 method with its own type parameter. */ + map(this: Wrap, f: (a0: number) => Pair): Wrap { + return new Wrap({ value: f(this.value), count: this.count }); + } + + eq(this: Wrap, other: Wrap): boolean { + return this.count === other.count && this.value.eq(other.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$Vec_u16(this: Wrap): number { + this.count = rt.u8.wrappingAdd(this.count, 1); + 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; + } + + 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(); + } + + 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(); + } + + 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$i16(value: number): Wrap { + return new Wrap({ value, count: 0 }); + } + + 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(); + } + + area$Meters(this: Wrap): bigint { + return this.value.area(); + } + + area$Shape(this: Wrap): bigint { + return Shape.area(this.value); + } +} + +/** 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 { + if (self.tag === "Left") { + const l = self._0; + return { tag: "Right", value: l }; + } 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); + } else { + return undefined; + } + }, + + fmt$u8_Point(self: Either, f: rt.Formatter): rt.Result { + if (self.tag === "Left") { + const __self0 = self._0; + 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) => __self02.fmt(f)).finish(); + } else { + return f.writeStr("Neither"); + } + }, + + fmt$Point_u8(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(); + } else if (self.tag === "Right") { + const __self02 = self.value; + return f.debugStruct("Right").field("value", (f: rt.Formatter) => rt.u8.display(__self02, f)).finish(); + } else { + return f.writeStr("Neither"); + } + }, + + left$u8_u16(self: Either): number | undefined { + if (self.tag === "Left") { + const l = self._0; + return l; + } else { + return undefined; + } + }, + + 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) => 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.u16.display(__self02, f)).finish(); + } else { + return f.writeStr("Neither"); + } + }, +}; + +/** Two parameters, one nested in another generic type. */ +export class Tagged { + key: K; + inner: Wrap; + all: Wrap[]; + + constructor(fields: { key: K; inner: Wrap; all: Wrap[] }) { + this.key = fields.key; + this.inner = fields.inner; + 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(); + } +} + +/** Each method once per instance: `Wrap` of a struct, an enum, a number, and itself. */ +export function methods(data: Uint8Array, out: rt.ByteVec): void { + const at = (i: number): number => { + return rt.option.unwrapOr(rt.slice.get(data, i), 0); + }; + let point: Wrap = Wrap.new$Point(new Point({ x: at(0), y: -2 })); + point.bump$Point(); + let byte: Wrap = Wrap.new$u8(at(1)); + byte.bump$u8(); + byte.bump$u8(); + const nested = Wrap.new$Wrap_Pair(Wrap.new$Pair(new Pair(at(2), -3n))); + const meters = new Wrap({ value: new Meters(BigInt(at(3))), count: at(4) }); + const shape = Wrap.new$Shape({ tag: "Rect", corner: rt.copy(point).intoInner(), width: at(5), height: 3 }); + put(out, rt.fmt.format([(f: rt.Formatter) => point.fmt$Point(f), " ", (f: rt.Formatter) => byte.fmt$u8(f), " ", (f: rt.Formatter) => nested.fmt$Wrap_Pair(f), " ", (f: rt.Formatter) => shape.fmt$Shape(f)])); + put(out, rt.fmt.format([rt.fmt.spec({ alternate: true }, (f: rt.Formatter) => nested.fmt$Wrap_Pair(f))])); + out.extendFromSlice(rt.u16.toBeBytes(byte.double())); + out.push(byte.get$u8()); + out.push(nested.get$Wrap_Pair().get$Pair()._0); + out.extendFromSlice(rt.u64.toBeBytes(meters.scaled$Meters())); + out.extendFromSlice(rt.u64.toBeBytes(shape.scaled$Shape())); + meters.describe$Meters(out); + shape.describe$Shape(out); + const mapped = rt.copy(byte).map((b: number): Pair => { + return new Pair(b, BigInt(at(6))); + }); + const arg2 = out; + const arg = mapped.eq(Wrap.new$Pair(new Pair(at(1), 0n))); + put(arg2, rt.fmt.format([(f: rt.Formatter) => mapped.fmt$Pair(f), " ", (f: rt.Formatter) => rt.fmt.bool(arg, f)])); + const eithers = [{ tag: "Left", _0: at(7) } as Either, { tag: "Right", value: Point.new(1, -1) } as Either, { tag: "Neither" } as Either]; + for (const either of rt.copy(eithers)) { + const flipped = Either.flip(either); + const arg5 = out; + const arg3 = Either.left$u8_Point(either); + const arg4 = Either.left$Point_u8(flipped); + put(arg5, rt.fmt.format([(f: rt.Formatter) => Either.fmt$u8_Point(either, f), " ", rt.fmt.spec({ alternate: true }, (f: rt.Formatter) => Either.fmt$Point_u8(flipped, f)), " ", (f: rt.Formatter) => rt.fmt.option(arg3, f, rt.u8.display), " ", (f: rt.Formatter) => rt.fmt.option(arg4, f, (value: Point, f: rt.Formatter) => value.fmt(f))])); + } + let list: Wrap = new Wrap({ value: [], count: 1 }); + list.value.push(at(10)); + list.bump$Vec_u16(); + const none = new Wrap({ value: undefined, count: 0 }); + const some = Wrap.new$Option_u8(rt.slice.get(data, 11)); + const err = new Wrap({ value: rt.Err({ tag: "Dot" } as Shape), count: 2 }); + const arg7 = out; + const arg6 = rt.option.unwrapOr(none.get$Option_u8(), some.count); + put(arg7, rt.fmt.format([(f: rt.Formatter) => list.fmt$Vec_u16(f), " ", (f: rt.Formatter) => none.fmt$Option_u8(f), " ", (f: rt.Formatter) => some.fmt$Option_u8(f), " ", (f: rt.Formatter) => err.fmt$Result_u8_Shape(f), " ", (f: rt.Formatter) => rt.u8.display(arg6, f)])); + const tagged = new Tagged({ key: { tag: "Right", value: 500 } as Either, inner: Wrap.new$i16(rt.i16.sub(at(8), 100)), all: rt.slice.toVec([Wrap.new$i16(-1), Wrap.new$i16(at(9))]) }); + const arg9 = out; + const arg8 = tagged.first(); + put(arg9, rt.fmt.format([(f: rt.Formatter) => tagged.fmt(f), " ", (f: rt.Formatter) => rt.fmt.option(arg8, f, (value: Wrap, f: rt.Formatter) => value.fmt$i16(f))])); + out.extendFromSlice(rt.i16.toBeBytes(tagged.inner.value)); + out.push(rt.option.unwrapOr(Either.left$u8_u16(tagged.key), 0)); +} + +//# sourceMappingURL=generics.ts.map diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 601416bc9..047779418 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -2,6 +2,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"; @@ -15,7 +16,7 @@ export function run(input: Uint8Array): rt.ByteVec { const kind = input[1]; const data = input.subarray(2, input.length - 0); const [op2, kind2] = [op, kind] as [number, number]; - const value = rt.u8.rem(op2, 26); + const value = rt.u8.rem(op2, 27); if (value === 0) { u8Op(kind2, data, out); } else if (value === 1) { @@ -86,8 +87,10 @@ export function run(input: Uint8Array): rt.ByteVec { derived(data, out); } else if (value === 24) { written(data, out); - } else { + } else if (value === 25) { panics(kind2, data, out); + } else { + methods(data, out); } return out; } diff --git a/ts/fixtures/lang/src/fmt.rs b/ts/fixtures/lang/src/fmt.rs index a4c3fc9d0..1d9647140 100644 --- a/ts/fixtures/lang/src/fmt.rs +++ b/ts/fixtures/lang/src/fmt.rs @@ -32,7 +32,7 @@ macro_rules! specs { }}; } -fn put(out: &mut Vec, s: &str) { +pub fn put(out: &mut Vec, s: &str) { out.extend_from_slice(s.as_bytes()); out.push(0xff); } diff --git a/ts/fixtures/lang/src/generics.rs b/ts/fixtures/lang/src/generics.rs new file mode 100644 index 000000000..6416ad34d --- /dev/null +++ b/ts/fixtures/lang/src/generics.rs @@ -0,0 +1,173 @@ +//! Methods on generic structs and enums, each instance its own method. + +use crate::fmt::{Pair, put}; +use crate::shapes::{Area, Meters, Point, Shape}; + +/// A generic struct, with methods on every instance, on some, and on one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Wrap { + pub value: T, + pub count: u8, +} + +impl Wrap { + pub fn new(value: T) -> Self { + Self { value, count: 0 } + } + + pub fn get(&self) -> &T { + &self.value + } + + pub fn bump(&mut self) -> u8 { + self.count = self.count.wrapping_add(1); + self.count + } + + pub fn into_inner(self) -> T { + self.value + } + + /// A method with its own type parameter. + pub fn map(self, f: impl FnOnce(T) -> U) -> Wrap { + Wrap { + value: f(self.value), + count: self.count, + } + } +} + +impl Wrap { + pub fn scaled(&self) -> u64 { + self.value.area().saturating_add(self.count as u64) + } +} + +impl Wrap { + pub fn double(&self) -> u16 { + self.value as u16 * 2 + } +} + +impl Area for Wrap { + const SIDES: u8 = T::SIDES; + + fn area(&self) -> u64 { + self.value.area() + } +} + +/// A generic enum, with a companion function per instance. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Either { + Left(L), + Right { value: R }, + Neither, +} + +impl Either { + pub fn left(&self) -> Option { + match *self { + Either::Left(l) => Some(l), + _ => None, + } + } + + pub fn flip(self) -> Either { + match self { + Either::Left(l) => Either::Right { value: l }, + Either::Right { value } => Either::Left(value), + Either::Neither => Either::Neither, + } + } +} + +/// Two parameters, one nested in another generic type. +#[derive(Debug)] +pub struct Tagged { + pub key: K, + pub inner: Wrap, + pub all: Vec>, +} + +impl Tagged { + fn first(&self) -> Option> { + self.all.first().copied() + } +} + +/// Each method once per instance: `Wrap` of a struct, an enum, a number, and itself. +pub fn methods(data: &[u8], out: &mut Vec) { + let at = |i: usize| data.get(i).copied().unwrap_or(0); + let mut point = Wrap::new(Point { + x: at(0) as i32, + y: -2, + }); + point.bump(); + let mut byte = Wrap::new(at(1)); + byte.bump(); + byte.bump(); + let nested = Wrap::new(Wrap::new(Pair(at(2), -3))); + let meters = Wrap { + value: Meters(at(3) as u64), + count: at(4), + }; + let shape = Wrap::new(Shape::Rect { + corner: point.into_inner(), + width: at(5) as u16, + height: 3, + }); + put(out, &format!("{point:?} {byte:?} {nested:?} {shape:?}")); + put(out, &format!("{nested:#?}")); + out.extend_from_slice(&byte.double().to_be_bytes()); + out.push(*byte.get()); + out.push(nested.get().get().0); + out.extend_from_slice(&meters.scaled().to_be_bytes()); + out.extend_from_slice(&shape.scaled().to_be_bytes()); + meters.describe(out); + shape.describe(out); + let mapped = byte.map(|b| Pair(b, at(6) as i64)); + put(out, &format!("{mapped:?} {:?}", mapped == Wrap::new(Pair(at(1), 0)))); + + let eithers: [Either; 3] = [ + Either::Left(at(7)), + Either::Right { value: Point::new(1, -1) }, + Either::Neither, + ]; + for either in eithers { + let flipped = either.flip(); + put( + out, + &format!("{either:?} {flipped:#?} {:?} {:?}", either.left(), flipped.left()), + ); + } + // Literals TypeScript would widen, as a class parameter infers from them. + let mut list = Wrap { + value: Vec::new(), + count: 1, + }; + list.value.push(at(10) as u16); + list.bump(); + let none = Wrap { + value: None::, + count: 0, + }; + let some = Wrap::new(data.get(11).copied()); + let err: Wrap> = Wrap { + value: Err(Shape::Dot), + count: 2, + }; + put( + out, + &format!("{list:?} {none:?} {some:?} {err:?} {:?}", none.get().unwrap_or(some.count)), + ); + + let tagged = Tagged { + key: Either::::Right { value: 500 }, + inner: Wrap::new(at(8) as i16 - 100), + all: [Wrap::new(-1), Wrap::new(at(9) as i16)].to_vec(), + }; + put(out, &format!("{tagged:?} {:?}", tagged.first())); + out.extend_from_slice(&tagged.inner.value.to_be_bytes()); + out.push(tagged.key.left().unwrap_or(0)); +} diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 15f2e579b..9facc6588 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -1,7 +1,7 @@ //! The entry point both sides of the differential test run. The first byte picks a //! case and the rest is its input. -use crate::{fmt, ints, shapes}; +use crate::{fmt, generics, ints, shapes}; /// Run one case. pub fn run(input: &[u8]) -> Vec { @@ -10,7 +10,7 @@ pub fn run(input: &[u8]) -> Vec { return out; }; let (op, kind) = (*op, *kind); - match op % 26 { + match op % 27 { 0 => ints::u8_op(kind, data, &mut out), 1 => ints::u16_op(kind, data, &mut out), 2 => ints::u32_op(kind, data, &mut out), @@ -46,7 +46,8 @@ pub fn run(input: &[u8]) -> Vec { 22 => fmt::strings(data, &mut out), 23 => fmt::derived(data, &mut out), 24 => fmt::written(data, &mut out), - _ => fmt::panics(kind, data, &mut out), + 25 => fmt::panics(kind, data, &mut out), + _ => generics::methods(data, &mut out), } out } diff --git a/ts/fixtures/lang/src/lib.rs b/ts/fixtures/lang/src/lib.rs index 5fc155cce..d6ddb1cee 100644 --- a/ts/fixtures/lang/src/lib.rs +++ b/ts/fixtures/lang/src/lib.rs @@ -5,6 +5,7 @@ //! `harness::run` is the entry point both sides of the differential test run. mod fmt; +mod generics; pub mod harness; mod ints; mod shapes; diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 96ee6677c..bc752c603 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -64,12 +64,26 @@ pub fn function<'a, 'tcx>( mutable: false, }, ); - if !method { - let ty = b.t.ty(ty, pat.span); - params.push(Param { - name: name.to_string(), - ty: Some(ty), - }); + match method { + // A generic class's method is one instance's, so `this` is that + // instance's type, under which its fields have their types. + true => { + let self_ty = b.t.self_ty(instance).expect("a method has a self type").peel_refs(); + let ty = b.t.ty(self_ty, pat.span); + if matches!(&ty, Type::Sym(_, args) if !args.is_empty()) { + params.push(Param { + name: name.to_string(), + ty: Some(ty), + }); + } + } + false => { + let ty = b.t.ty(ty, pat.span); + params.push(Param { + name: name.to_string(), + ty: Some(ty), + }); + } } } (Some(pat), false) => { @@ -2021,7 +2035,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ts::Ctor::Positional => { let mut ordered: Vec> = vec![None; variant.fields.len()]; for (f, value) in adt.fields.iter().zip(values) { - ordered[f.name.index()] = Some(value.typed()); + ordered[f.name.index()] = Some(field_arg(tcx, &variant.fields[f.name], value)); } let args = ordered .into_iter() @@ -2046,7 +2060,10 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { .fields .iter() .zip(values) - .map(|(f, value)| (Key::Field(fields[f.name.index()]), value.typed())) + .map(|(f, value)| { + let value = field_arg(tcx, &variant.fields[f.name], value); + (Key::Field(fields[f.name.index()]), value) + }) .collect(); if let Some(base) = &base { for (i, field) in variant.fields.iter().enumerate() { @@ -2295,7 +2312,9 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { match info.repr { AdtRepr::Class { .. } => Expr::New( Box::new(Expr::Sym(info.sym)), - values.into_iter().map(Expr::typed).collect(), + (adt.variant(variant).fields.iter().zip(values)) + .map(|(field, value)| field_arg(tcx, field, value)) + .collect(), ), AdtRepr::Tags => { let ts_ty = self.t.ty(ty, span); @@ -2437,3 +2456,13 @@ fn kind_name(kind: &ExprKind<'_>) -> String { let debug = format!("{kind:?}"); debug.split([' ', '(', '{']).next().unwrap_or("?").to_string() } + +/// A field's value as a class's constructor takes it: without an outer `as` where the +/// field's type gives the value its type, but not where TypeScript infers a class +/// parameter from it, which would widen a literal. +fn field_arg<'tcx>(tcx: ty::TyCtxt<'tcx>, field: &ty::FieldDef, value: Expr) -> Expr { + match tcx.type_of(field.did).instantiate_identity().skip_norm_wip().has_param() { + true => value, + false => value.typed(), + } +} diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 7be26e2eb..36989cc31 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -471,24 +471,36 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { /// What tells this instance apart from others of the same name. fn suffix(&self, instance: Instance<'tcx>) -> String { + let tcx = self.tcx; let mut parts = Vec::new(); let def_id = instance.def_id(); - if let Some(imp) = self.tcx.trait_impl_of_assoc(def_id) { - let trait_ref = self.tcx.impl_trait_ref(imp).skip_binder(); + if let Some(imp) = tcx.trait_impl_of_assoc(def_id) { + let trait_ref = tcx.impl_trait_ref(imp).skip_binder(); let args = self.subst(instance.args, trait_ref.args); - parts.extend(args.types().skip(1).map(|t| short_name(self.tcx, t))); + parts.extend(args.types().skip(1).map(|t| short_name(tcx, t))); } + // The type whose class or companion this is on goes without saying, but not its + // arguments, such as a default method's on `Wrap`. + let owner = self + .self_ty(instance) + .map(Ty::peel_refs) + .filter(|t| matches!(t.kind(), ty::Adt(adt, _) if adt.did().is_local())); // A closure or function type follows from the others, and has no name. let named = |t: &Ty<'tcx>| !matches!(t.kind(), ty::Closure(..) | ty::FnDef(..) | ty::FnPtr(..)); - parts.extend(instance.args.types().filter(named).map(|t| short_name(self.tcx, t))); + for t in instance.args.types().filter(named) { + match (owner == Some(t), t.kind()) { + (true, ty::Adt(_, args)) => parts.extend(args.types().map(|t| short_name(tcx, t))), + _ => parts.push(short_name(tcx, t)), + } + } parts.dedup(); // Impls of traits without arguments, such as `Display::fmt` and `Debug::fmt`, are // told apart by their trait. if parts.is_empty() - && let Some(imp) = self.tcx.trait_impl_of_assoc(def_id) + && let Some(imp) = tcx.trait_impl_of_assoc(def_id) { - let trait_id = self.tcx.impl_trait_ref(imp).skip_binder().def_id; - parts.push(self.tcx.item_name(trait_id).to_string()); + let trait_id = tcx.impl_trait_ref(imp).skip_binder().def_id; + parts.push(tcx.item_name(trait_id).to_string()); } parts.join("_") } @@ -942,9 +954,16 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } /// A short name for a type, to tell instances apart. -fn short_name(tcx: TyCtxt<'_>, ty: Ty<'_>) -> String { +fn short_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String { match ty.kind() { - ty::Adt(adt, _) => tcx.item_name(adt.did()).to_string(), + // Its arguments, but not defaults such as a `Vec`'s allocator. + ty::Adt(adt, args) => { + let args = tcx.generics_of(adt.did()).own_args_no_defaults(tcx, args); + std::iter::once(tcx.item_name(adt.did()).to_string()) + .chain(args.iter().filter_map(|arg| arg.as_type()).map(|t| short_name(tcx, t))) + .collect::>() + .join("_") + } ty::Ref(_, inner, _) => short_name(tcx, *inner), ty::Tuple(tys) => tys.iter().map(|t| short_name(tcx, t)).collect::>().join("_"), ty::Array(elem, _) | ty::Slice(elem) => format!("{}s", short_name(tcx, *elem)), From fb5314e93392c8c89d09d08ec07193e8b3206670 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:36:20 -0700 Subject: [PATCH 3/3] feat(ts): name generic instances by their arguments, document, and finish the quest Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 1 - quest/m2/ts-generic-methods.md | 16 ---------------- quest/m2/ts-model.md | 1 - ts/README.md | 10 ++++++++-- ts/fixtures/lang/src/generics.rs | 14 ++++++++------ ts/fixtures/lang/src/lib.rs | 2 +- ts/src/lower/body.rs | 7 ++++++- ts/src/lower/mod.rs | 3 ++- 8 files changed, 25 insertions(+), 29 deletions(-) delete mode 100644 quest/m2/ts-generic-methods.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 2370efa34..e55817c51 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -24,7 +24,6 @@ deletes the quests that follow it. - [Collections](/quest/m2/ts-collections.md) - maps, sets, and queues keep Rust's key semantics - [Tail loops](/quest/m2/ts-tail-loop.md) - a `loop` ending a function body translates - [Formatting impls of root types](/quest/m2/ts-root-fmt.md) - a root type brings its `Display` and `Debug` into the output -- [Methods on generic types](/quest/m2/ts-generic-methods.md) - generic classes' methods type-check, derived `Debug` included - [Empty braced structs](/quest/m2/ts-empty-struct.md) - `struct E {}` passes `tsc` - [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 diff --git a/quest/m2/ts-generic-methods.md b/quest/m2/ts-generic-methods.md deleted file mode 100644 index 1b716e3b8..000000000 --- a/quest/m2/ts-generic-methods.md +++ /dev/null @@ -1,16 +0,0 @@ -# [M] Methods on generic types in the TypeScript translator - -## Goal - -[rust2-ts](/ts/README.md)'s output for methods on a generic struct or enum -type-checks under `tsc`, derived `Debug` included, proven by differential tests -on generic fixtures. - -## Plan - -Decided with the maintainer on 2026-10-23, from the formatting PR (#8): each -monomorphized method lands on the one generic class, so a body calls an -instance's method on a field typed `T` (such as `this.value.fmt$Pair(f)`), which -`tsc` rejects. moq-net's model has generic types, so the model quest needs this. - -Public API: the translator's output for generic types. diff --git a/quest/m2/ts-model.md b/quest/m2/ts-model.md index 9a3f61da0..da2ecd44c 100644 --- a/quest/m2/ts-model.md +++ b/quest/m2/ts-model.md @@ -38,5 +38,4 @@ Public API: the translator's output for moq-net's model. - [Iterators](/quest/m2/ts-iter.md) - the model's adaptor chains - [Collections](/quest/m2/ts-collections.md) - the model's maps and queues - [Tail loops](/quest/m2/ts-tail-loop.md) - 62 moq-net sites end a function in a `loop` -- [Methods on generic types](/quest/m2/ts-generic-methods.md) - the model's generic types - [Formatting impls of root types](/quest/m2/ts-root-fmt.md) - callers print the model's errors diff --git a/ts/README.md b/ts/README.md index 1d64e5e21..184e2ad48 100644 --- a/ts/README.md +++ b/ts/README.md @@ -76,7 +76,9 @@ prints it. Functions and members are camelCase. Functions are monomorphized: each instance is its own function, and instances that share a name are suffixed by type, as in -`roundtripLite$Group`. Types are translated once, generically. A `Copy` struct, tuple, or +`roundtripLite$Group` or `get$Wrap_Pair`. Types are translated once, generically, so a +generic class holds a method per instance, each declaring the instance it takes as +`this`: `fmt$Pair(this: Wrap, f: rt.Formatter)`. A `Copy` struct, tuple, or array, or an `Option` or `Result` holding one, is copied where Rust copies it, since JS would share the object. @@ -87,6 +89,10 @@ Imports name the `.ts` file, which Node, Bun, and bundlers run as is. A `tsc` bu - 64-bit integers are native `bigint`: lossless and readable. A pair of `u32` halves is faster but waits until `just ts bench` measures `bigint` as the cost. +- A generic type is one class or union, the type TS callers name, and a method on it is + one instance's, typed by its `this`. A class per instance (`Wrap$Pair`) would rename + the type for callers, and TS generics with trait dictionaries would undo + monomorphization. - `Result` is a plain `{ ok, value } | { ok, error }` object rather than an exception, so `?` and `match` keep Rust's control flow exactly. - Bodies lower from THIR, which keeps loops, `match`, and `?` shaped as written. It does @@ -125,7 +131,7 @@ built natively for wasm32 and run beside its translation on the same inputs by - `codec` vendors moq-net's sync codec, which a harness outside the crate could not reach, and writes its errors' `Display` and `Debug`. - `lang` covers every integer width's arithmetic and casts, control flow, patterns, - `Copy` aggregates, and formatting. + `Copy` aggregates, formatting, and methods on generic types. - `reject` holds constructs outside the subset; its expected errors are `expected.txt`, and its expected census is `census.md`. diff --git a/ts/fixtures/lang/src/generics.rs b/ts/fixtures/lang/src/generics.rs index 6416ad34d..77ee85840 100644 --- a/ts/fixtures/lang/src/generics.rs +++ b/ts/fixtures/lang/src/generics.rs @@ -99,10 +99,7 @@ impl Tagged { /// Each method once per instance: `Wrap` of a struct, an enum, a number, and itself. pub fn methods(data: &[u8], out: &mut Vec) { let at = |i: usize| data.get(i).copied().unwrap_or(0); - let mut point = Wrap::new(Point { - x: at(0) as i32, - y: -2, - }); + let mut point = Wrap::new(Point { x: at(0) as i32, y: -2 }); point.bump(); let mut byte = Wrap::new(at(1)); byte.bump(); @@ -131,7 +128,9 @@ pub fn methods(data: &[u8], out: &mut Vec) { let eithers: [Either; 3] = [ Either::Left(at(7)), - Either::Right { value: Point::new(1, -1) }, + Either::Right { + value: Point::new(1, -1), + }, Either::Neither, ]; for either in eithers { @@ -159,7 +158,10 @@ pub fn methods(data: &[u8], out: &mut Vec) { }; put( out, - &format!("{list:?} {none:?} {some:?} {err:?} {:?}", none.get().unwrap_or(some.count)), + &format!( + "{list:?} {none:?} {some:?} {err:?} {:?}", + none.get().unwrap_or(some.count) + ), ); let tagged = Tagged { diff --git a/ts/fixtures/lang/src/lib.rs b/ts/fixtures/lang/src/lib.rs index d6ddb1cee..751b9569d 100644 --- a/ts/fixtures/lang/src/lib.rs +++ b/ts/fixtures/lang/src/lib.rs @@ -1,6 +1,6 @@ //! The language the driver translates, exercised against native Rust: every integer //! width's arithmetic and casts, control flow, patterns, `Copy` aggregates, closures, -//! traits, formatting, and the standard library calls it maps. +//! traits, generic types, formatting, and the standard library calls it maps. //! //! `harness::run` is the entry point both sides of the differential test run. diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index bc752c603..10a20640f 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -2461,7 +2461,12 @@ fn kind_name(kind: &ExprKind<'_>) -> String { /// field's type gives the value its type, but not where TypeScript infers a class /// parameter from it, which would widen a literal. fn field_arg<'tcx>(tcx: ty::TyCtxt<'tcx>, field: &ty::FieldDef, value: Expr) -> Expr { - match tcx.type_of(field.did).instantiate_identity().skip_norm_wip().has_param() { + match tcx + .type_of(field.did) + .instantiate_identity() + .skip_norm_wip() + .has_param() + { true => value, false => value.typed(), } diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 36989cc31..d2ba91d48 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -2,7 +2,8 @@ //! //! Translation starts from the configured roots and follows what they reach. Functions //! are monomorphized: each instance becomes its own TypeScript function, so a trait -//! call is always a direct call. Types are translated once, generically. +//! call is always a direct call. Types are translated once, generically: a generic +//! class's method is one instance's, and declares that instance as its `this`. mod body; mod consts;