Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions tslang/docs/classes-as-values-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# Classes as values, and local classes that capture: design

Status: **proposed, not implemented**. Written 2026-10-29, to be picked up later.

## 1. What works and what fails today

**Works:** a class used under another name at compile time.

```ts
const C = A; // an alias: `new C(3)` is `new A(3)`
const D = class { v = 7; };
```

**Fails:** a class passed or stored as a run-time value.

```ts
function make(c: typeof A, n: number) { return new c(n); }
make(A, 1); make(B, 1); // B extends A
```

This fails with "failed to legalize operation 'ts.ClassRef' that was explicitly marked illegal". `ts.ClassRef` names a class at compile time only. No lowering turns it into a value, so a class given to a parameter, stored in a variable, an array or a field, or returned, has nothing to lower to.

**Fails:** a class declared in a function whose members read the function's locals.

```ts
function counter(start: number) {
class Counter { n = start; inc() { this.n += start; return this.n; } }
return new Counter();
}
counter(2).inc(); // "Expected 1 arguments, but got 0."
```

The members are lifted to module functions that take the captured variables as an extra parameter, the way an arrow function's body does. A call through the object (`c.inc()`), or the field initializers run by `new`, never pass it.

## 2. Classes as values

### 2.1 Representation

A class value is a pointer to the class's vtable. Every vtable already has the pieces a value needs: `.instanceOf`, `.new` (`NEW_METHOD_NAME`, allocation), `.rtti` and the methods. `typeof A` becomes a type, `ClassValueType<A>`, lowered to that pointer.

- **Assignability:** `B`'s value is assignable to `typeof A` when `B` extends `A` and its constructor accepts `A`'s arguments. TypeScript checks the construct signatures structurally; nominal "extends" plus a parameter check is enough here.
- **`ts.ClassRef` used as a value:** it becomes the address of the class's vtable (`ts.AddressOf @A..vtbl`), as the object constructor already stores it.

### 2.2 Construction through a value

`new c(n)` with `c: typeof A` takes three steps:
1. **Allocate:** call the vtable's `.new` slot.
2. **Construct:** call the constructor, which must be reachable from the vtable too. A new slot, `.constructor`, typed as `A`'s constructor; a subclass fills it with its own constructor, which takes the same arguments for an assignable class.
3. **Result:** the result type is `A`.

Static members (`c.create()`, `c.count`) need slots of their own, or a second table the vtable points to. The first version can leave them out: report "static member through a class value is not supported".

### 2.3 Ownership

- **The class value owns nothing:** it points at static data, like a string literal. It is immortal under rc and own.
- **The constructed object:** it is a fresh owned result, like `new A(n)`.

### 2.4 Cross-module

A vtable of a class from a `-shared` library is already addressable (`isDynamicImport`), so a class value can refer to it. The new `.constructor` slot changes the vtable layout. Classes compiled by an older compiler would not have it, so the slot goes at the end, and the layout contract in `docs/interface-vtable-simplification-design.md` gains one entry.

### 2.5 Tests

- a factory that takes `typeof A` and is given `A` and a subclass;
- an array of class values;
- `instanceof` against a class value;
- under gc, rc, none and own.

## 3. Local classes that capture

### 3.1 Options

**A. Captures in the instance.** The class's storage gains a hidden field, `.captured`, holding the capture box (as an object literal's `.captured` field does, `MLIRGenExpressions.cpp`).
- **Filling it:** `new Counter()` in the declaring function fills it from the current box.
- **Reading it:** members read the captured variables through `this..captured` instead of an extra parameter, so a call through the object passes nothing new.
- **Pros:** works for methods, accessors, field initializers and the constructor, and for an object that outlives the function (`return new Counter()`).

**B. One class per declaring call.** Instantiate the class's functions again per capture box. That's impossible without run-time code generation.

**C. Reject.** Report an error for a member of a local class that names a local of the enclosing function, instead of the misleading arity error.

### 3.2 Recommendation

1. **Now:** do C. It replaces "Expected 1 arguments, but got 0" with an error that names the captured variable.
2. **Then:** A.
- **Boxes are reused:** they're the same capture boxes arrow functions use (`ts.Capture`, `__capture_box`).
- **Under own:** the box is owned by the instance and freed with it. The instance's release routine releases `.captured`, the way a closure's box routine does (spec 2.5 in the own design document).
- **Under rc:** the box is counted like any other field.

### 3.3 Interaction with classes as values

A local class used as a value (`return Counter`) carries its captures. Its value then has to be a pair, `{vtable, box}`, not the vtable alone. Keep the two features apart at first: class values only for module-level classes, and an error for a local class that captures and is used as a value.

## 4. Non-goals

- `abstract new () => A` construct signatures and mixins (`function Mixin<T extends new (...a: any[]) => {}>(Base: T)`): these build on class values but need generic construct signatures. A follow-up.
- `typeof` on a class value returning `"function"` as in JavaScript: tslang's `typeof` reports its own kind names. Decide when class values land.
78 changes: 78 additions & 0 deletions tslang/docs/generic-interface-methods-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Generic methods in interfaces (and virtual generic class methods): design

Status: **proposed, not implemented**. Written 2026-10-29, to be picked up later.

## 1. What fails today

```ts
interface Mapper { map<T>(x: T): T; }
class Id implements Mapper { map<T>(x: T): T { return x; } }
const m: Mapper = new Id();
m.map<number>(5);
```

- **The interface:** compiling it fails with "Generic method 'map' in the interface is not allowed". `getInterfaceMethodNameAndType` (`lib/TypeScript/MLIRGenImpl.h`) refuses any method signature with type parameters.
- **A class hierarchy, worse because it's silent:**

```ts
class Id { map<T>(x: T): T { return x; } }
class Twice extends Id { map<T>(x: T): T { print("twice"); return x; } }
const a: Id = new Twice();
a.map<number>(5); // calls Id.map: "twice" is never printed
```

A generic class method is not virtual. Each call instantiates the method of the *static* type's class (`staticGenericMethods`, `MLIRGenClasses.cpp`), so an override in a subclass is never reached through a base reference. No error or warning says so.

## 2. Why it is not simply a vtable slot

A vtable slot holds one function pointer. A generic method has no single function, only one instantiation per type argument, and each is produced where a call names it (monomorphization).

- **Through an interface or a base class:** the caller does not know which class implements the method, so it cannot instantiate the right body.
- **In the implementer:** the class does not know which type arguments callers will use (other modules included), so it cannot fill a slot per instantiation ahead of time.

## 3. Options

**A. Erased slot.** The interface (or base-class) vtable gets one slot per generic method, holding an instantiation in which each type parameter is `any`.
- **At the call site:** box the arguments whose type is a type parameter, call through the slot, and unbox the result to the call's type argument. The unbox is checked, as `<T>anyValue` is.
- **In the implementer:** the class provides the `any` instantiation of its own method for the slot. Direct calls on a known class keep the monomorphized fast path they use today.
- **Pros:** works across modules and with separately compiled implementers.
- **Cons:** boxing costs, and the body runs on `any`. A body that relies on the type parameter's real type (`sizeof<T>()`, `new T()` through a constraint, arithmetic on `T extends number`) changes behaviour in the erased form. Such methods would have to be rejected for virtual dispatch with a clear error.

**B. Closed-world instantiation table.** Collect every (method, type argument) pair called through an interface or base type in the program. Give each pair a slot, appended to every implementer's vtable.
- **Pros:** no boxing; the bodies run at their real types.
- **Cons:** needs whole-program knowledge. It breaks for `-shared` libraries and the JIT cache (modules compiled apart), and the slot layout changes as programs grow. Unfit for this compiler's cross-module model (`docs/interface-vtable-simplification-design.md`).

**C. Dictionary passing.** Instantiate a generic method once, with a hidden argument that carries type information (size, descriptor, retain/release routines). This is what Swift does for unspecialized generics.
- **Pros:** no boxing of values; one body per method.
- **Cons:** a large change. Every generic body would need to lower against a runtime type description instead of concrete MLIR types, and the ownership passes (`-mm=own`, `-mm=rc`) reason about concrete types throughout.

**D. Keep rejecting, but say so.** Report an error for a generic method overridden in a subclass, instead of silently calling the base method. Interfaces keep their current error.

## 4. Recommendation

1. **Now:** do D for classes. It turns a silent wrong call into an error. That's cheap, and correct regardless of what follows.
2. **Then:** A for interfaces and virtual class methods, limited to methods whose bodies the erased form can run unchanged:
- type parameters used only as values: stored, passed on, returned;
- no `sizeof<T>`, no `new` through a constraint, no numeric operators on `T`.

A method outside that set gets a clear error at its declaration.
3. **C** is the long-term general answer, but it is a project of its own.

## 5. Work involved for A

- **Interface declaration:** for each generic method, a slot whose function type has every type parameter replaced by `any` (`getInterfaceMethodNameAndType`, `InterfaceInfo::methods`).
- **Implementer:** when a class's vtable is built for the interface (`getVirtualTable`, `mlirGenObjectVirtualTableDefinitionForInterface`), instantiate the class method with `any` for each type parameter. Then put that symbol in the slot.
- **Call site:** `m.map<number>(5)` through an interface or a base type becomes three steps: cast the arguments to `any`, make an indirect call through the slot, and cast the result to `number` (`castFromAny`, checked).
- **Base classes:** the class vtable gains the same erased slot for each generic method, and an override fills it. A call through a base-class reference uses it; a call on the exact class keeps today's direct instantiation.
- **Ownership under -mm=own:** a boxed argument is a fresh `any` the callee borrows. The result is unboxed into a value the caller owns. Both are existing patterns (spec 59, casts to `any`).
- **Tests:**
- an interface call with two type arguments;
- a subclass override reached through a base reference;
- a cross-module implementer (`-shared`);
- the rejection of a body that uses `sizeof<T>`;
- each case under gc, rc, none and own.

## 6. Non-goals

- Generic *interfaces* (`interface Box<T>`) already work: they are instantiated per type argument. This document is only about generic *methods*.
- Making generic class methods virtual where nothing overrides them: a direct instantiation stays faster.
4 changes: 3 additions & 1 deletion tslang/docs/tuple-object-shape-ambiguity-design.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# `isObjectShapedTuple` structural ambiguity: design

Status: **proposed, not implemented** — written for later review. Triggered by
Status: **proposed, not implemented** — written for later review. Re-checked 2026-10-29: still open,
`isObjectShapedTuple` (now `MLIRPrinter.h:288`) unchanged; the recommendation in §6 stands, and the first
step is the test §7 names, which pins the wrong output before any fix. Triggered by
a code-review comment on `MLIRPrinter.h:232` during the cross-module
class-extends work (`fix/cross-module-class-extends-crash` branch). A narrow
symptom of the problem (numeric field ids) was already patched (see §4); this
Expand Down
70 changes: 70 additions & 0 deletions tslang/lib/TypeScript/MLIRGenCast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1758,6 +1758,59 @@ namespace mlirgen
return std::nullopt;
}

// The first interface member of a union whose every required field and method an object literal, a
// tuple or a class object has, by name; null for another value or when none fits.
mlir::Type MLIRGenImpl::interfaceMemberFitting(mlir_ts::UnionType unionType, mlir::Type valueType)
{
if (!isa<mlir_ts::ObjectType, mlir_ts::TupleType, mlir_ts::ConstTupleType, mlir_ts::ClassType>(valueType))
{
return mlir::Type();
}

// a field or a method of that name, as `"k" in v` asks of one value (mlirGenInLogic)
auto has = [&](mlir::Attribute id) { return !!mth.getFieldTypeByFieldName(valueType, id); };

std::function<bool(InterfaceInfo::TypePtr)> fits = [&](InterfaceInfo::TypePtr interfaceInfo) {
for (auto &extent : interfaceInfo->extends)
{
if (!fits(std::get<1>(extent)))
{
return false;
}
}

for (auto &method : interfaceInfo->methods)
{
if (!method.isConditional && !has(builder.getStringAttr(method.name)))
{
return false;
}
}

for (auto &field : interfaceInfo->fields)
{
if (!field.isConditional && !has(field.id))
{
return false;
}
}

return true;
};

for (auto member : unionType.getTypes())
{
auto interfaceType = dyn_cast<mlir_ts::InterfaceType>(member);
auto interfaceInfo = interfaceType ? getInterfaceInfoByFullName(interfaceType.getName().getValue()) : InterfaceInfo::TypePtr();
if (interfaceInfo && fits(interfaceInfo))
{
return member;
}
}

return mlir::Type();
}

std::optional<ValueOrLogicalResult> MLIRGenImpl::castToTaggedUnionType(mlir::Location location, mlir::Type type, mlir::Value value, mlir::Type valueType, const GenContext &genContext)
{
if (auto unionType = dyn_cast<mlir_ts::UnionType>(type))
Expand All @@ -1778,6 +1831,15 @@ namespace mlirgen
}
}

// an object literal, a tuple or a class object given to a union of interfaces
// (`move({ swim: () => "s" })` for `Fish | Bird`): it becomes the first interface it has every member of, and the
// union's tag says which (`"swim" in a`)
if (auto memberType = interfaceMemberFitting(unionType, valueType))
{
CAST(value, location, memberType, value, genContext);
return V(builder.create<mlir_ts::CastOp>(location, type, value));
}

// one member and null (`{ k: number } | null`): what is not null is that member -
// an object literal `{ k: 5 }`, whose field is an s32, is converted to it
if (!isa<mlir_ts::NullType>(valueType) && types.size() == 2
Expand Down Expand Up @@ -2149,6 +2211,14 @@ namespace mlirgen
entryBlock.getArguments().take_front(inInputs.size()));
if (hasResult)
{
// the callee's result is the thunk's, handed on as `return f(x)` hands it: owned, and
// taken over by the return (a string `map` builds came back as a second reference)
if (mth.ownsHeapMemory(noLocation, results.front()))
{
callOp->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr());
callOp->setAttr(OWNED_RESULT_CONSUMED_ATTR_NAME, builder.getUnitAttr());
}

builder.create<mlir_ts::ReturnValOp>(noLocation, callOp.getResult(0), entryOp.getReference());
}

Expand Down
16 changes: 16 additions & 0 deletions tslang/lib/TypeScript/MLIRGenGenerics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,14 @@ namespace mlirgen
if (tempfuncType.size() > 0 || mth.getReturnsFromFuncRef(templateType).size() > 0)
{
auto funcType = mth.getParamsFromFuncRef(concreteType);
// a closure is its function bound over its captures, which its first parameter takes: not one
// the callback type has (`each(xs, (v) => { s += v; })` for `f: (v: T, i: number) => void`
// paired `T` with the captures)
if (isa<mlir_ts::BoundFunctionType>(concreteType) && !funcType.empty())
{
funcType = funcType.drop_front();
}

if (funcType.size() > 0 || tempfuncType.size() == 0)
{
inferTypeFuncType(location, tempfuncType, funcType, results, genContext);
Expand Down Expand Up @@ -792,6 +800,14 @@ namespace mlirgen
return {mlir::failure(), true};
}

// ...and so does the arrow's type built again here
if (auto funcType = dyn_cast<mlir_ts::FunctionType>(newArrowFuncType);
funcType && argOp.getDefiningOp<mlir_ts::CreateBoundFunctionOp>() && funcType.getNumInputs() > 0)
{
newArrowFuncType = mlir_ts::FunctionType::get(builder.getContext(), funcType.getInputs().drop_front(),
funcType.getResults(), funcType.isVarArg());
}

// infer second type when ArrowType is fully built
StringMap<mlir::Type> inferredTypes;
inferType(location, paramType, newArrowFuncType, inferredTypes, genericTypeGenContext);
Expand Down
2 changes: 2 additions & 0 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -14722,6 +14722,8 @@ class MLIRGenImpl
// reports which part of a function signature does not match the one it is assigned to
void emitFunctionTypeMismatch(mlir::Location location, mlir::Type valueType, mlir::Type type, MatchResult match);

mlir::Type interfaceMemberFitting(mlir_ts::UnionType unionType, mlir::Type valueType);

mlir::Value fewerParametersThunk(mlir::Location location, mlir::Value value, mlir::Type type);

// optional
Expand Down
Loading
Loading