diff --git a/quest/m2/README.md b/quest/m2/README.md index d70161207..0fb292e12 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 -- [Methods on generic types](/quest/m2/ts-generic-methods.md) - generic classes' methods type-check, derived `Debug` included - [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 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 23ff5d609..c98a0b5dc 100644 --- a/quest/m2/ts-model.md +++ b/quest/m2/ts-model.md @@ -37,4 +37,3 @@ Public API: the translator's output for moq-net's model. - [Shared ownership](/quest/m2/ts-shared.md) - kio's waiters are `Arc`/`Weak` with observable counts - [Iterators](/quest/m2/ts-iter.md) - the model's adaptor chains - [Collections](/quest/m2/ts-collections.md) - the model's maps and queues -- [Methods on generic types](/quest/m2/ts-generic-methods.md) - the model's generic types diff --git a/ts/README.md b/ts/README.md index 4b4fb73c4..0acd5c4ed 100644 --- a/ts/README.md +++ b/ts/README.md @@ -81,7 +81,9 @@ would: `rt.fmt.toString((f) => DecodeError.fmt$Display(err, f))` and 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. @@ -92,6 +94,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 @@ -130,8 +136,9 @@ 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. Its differential test runs through `caller.ts`, a - hand-written caller that also prints a `printable` error nothing translated prints. + `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 + translated prints. - `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/expected/generics.ts b/ts/fixtures/lang/expected/generics.ts new file mode 100644 index 000000000..7be0d9187 --- /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 { Pair, put } 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 368d5c9a6..7c2f5e660 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..77ee85840 --- /dev/null +++ b/ts/fixtures/lang/src/generics.rs @@ -0,0 +1,175 @@ +//! 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 b702b1df3..433a5e07a 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}; /// The native side's entry: [`run`], except that a case starting with 0xff prints a /// [`fmt::Fault`], which the translated side prints from TypeScript in `caller.ts`. @@ -19,7 +19,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), @@ -55,7 +55,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 934c4b0e0..3e02e4881 100644 --- a/ts/fixtures/lang/src/lib.rs +++ b/ts/fixtures/lang/src/lib.rs @@ -1,11 +1,12 @@ //! 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, and //! `fmt::Fault` an error only `caller.ts` prints. 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 6e015386e..835c189bc 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) => { @@ -2050,7 +2064,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() @@ -2075,7 +2089,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() { @@ -2324,7 +2341,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); @@ -2466,3 +2485,18 @@ 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 b6dc553d6..1f1bcc162 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; @@ -539,24 +540,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("_") } @@ -1017,9 +1030,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)),