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
60 changes: 59 additions & 1 deletion tslang/docs/classes-as-values-design.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Classes as values, and local classes that capture: design

Status: **proposed, not implemented**. Written 2026-10-29, to be picked up later.
Status: **class values implemented for module-level classes; local classes that capture are an error
(option C)** (2026-10-29); see §5. Captures in the instance (option A) are not done.

## 1. What works and what fails today

Expand Down Expand Up @@ -95,3 +96,60 @@ A local class used as a value (`return Counter`) carries its captures. Its value

- `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.

## 5. What is implemented

**The value.** `ClassValueType<A>` (`class_value<...>`, printed `typeof A`) is what `typeof A` of a class
gives (`typeOfQueried`). It is laid out as a tuple of four opaque pointers
(`MLIRTypeHelper::getClassValueStorageType`), not as a vtable pointer alone:
- **`.vtable`:** the class's vtable. An abstract class has one too, though no instance carries it: its
statics are read through it, and its abstract methods' and interfaces' slots are null.
- **`.new`:** the class's `.new`, which allocates an instance and sets its vtable; null for an abstract class.
- **`.constructor`:** the class's constructor, or null for none.
- **`.rtti`:** the class's rtti, which every class has and no two share.

A pair-or-more layout needs no new vtable slot, so no class's vtable changes (§2.4 is moot). `ts.Cast`
between the value and that tuple, or to the value of a base class, lowers to nothing.

**Making one** (`castToClassValue`, `mlirGenClassValue`):
- **Where:** a class name becomes a value only where a `typeof A` is expected - a parameter, a typed
variable or field, an array element, a return. `const C = A` stays a compile-time alias.
- **Assignable:** `B` is a value of `typeof A` when it extends `A` and its constructor takes the same
parameters (fewer is allowed).
- **Another module's class** is a value too. A shared library's (-shared) has its `.new`, constructor and
rtti behind the pointers the importer resolves at load time, and its vtable is looked up in the library
by name. A class without a constructor of its own, whose base is a library's, takes the base's through
that pointer. Through the value, a library class's static field is read where the library's vtable slot
points: the field itself, not the importer's pointer to it.
- **Not yet:** a @value class or a @cpp class can't be a value.

**Using one:**
- **`new c(args)`** (`NewClassInstanceFromClassValue`): the arguments are cast to `A`'s constructor's
parameters, and `.new` is called through the value, its result marked owned and fresh. Then the
constructor is called with the instance first, when there is one, as any call is made (spread
arguments, a rest parameter, optional parameters). A value of an abstract class's type is an error.
- **`==` / `!=`:** compare the rtti; a class named beside a value is its value.
- **`typeof`** of a class value is `"function"`.
- **A static method** is called through the value's vtable (ADD_STATIC_MEMBERS_TO_VTABLE). A subclass's
static method of the same name takes over the slot, so `c.label()` is the label of the class `c` holds.
- **A static field** is read through the vtable too. One that a subclass declares again, of the same
type, takes over the base's slot (`ClassInfo::getVirtualTable`), so it is the field of the class the
value holds; the compiler's own (`.rtti`, `.size`) keep a slot each.
- Any other member through a value is an error.

**Ownership:** the value owns nothing (its parts are static data and functions). The instance `new` makes
through it is a fresh owned result.

**Local classes (option C).** A method, constructor or accessor of a class declared in a function that reads
one of the function's locals is an error naming the variable, in place of "Expected 1 arguments, but got
0". A field initializer of a class without a constructor still fails as it did ("value defined outside the
region"): the initializers reach the implicit constructor after captures are found.

**Tests:**
- **`00class_values`:** a factory, an array, a return, a field, a class without a constructor, a subclass
without its own constructor, equality, abstract classes, `typeof`, static fields and methods through
the value (a subclass's, an inherited one, an abstract class's own); under
gc, rc, none and own.
- **`import_class_values`** + **`export_class_values`:** a library's classes, and one of this module extending
one, as values both ways; linked, -shared and -jit -shared, under every memory model.
- **`class_value_constructor_error`** and **`class_local_capture_error`:** the errors.
4 changes: 4 additions & 0 deletions tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,10 @@
#define TYPE_DESCR_NAME ".type_descr"
#define NEW_METHOD_NAME ".new"
#define NEW_CTOR_METHOD_NAME ".new_ctor"
// the fields of a class value's storage tuple (ClassValueType), beside NEW_METHOD_NAME
#define CLASS_VALUE_VTABLE_NAME ".vtable"
#define CLASS_VALUE_CONSTRUCTOR_NAME ".constructor"
#define CLASS_VALUE_RTTI_NAME ".rtti"
#define LENGTH_FIELD_NAME "length"
#define INDEX_ACCESS_FIELD_NAME ".index"
#define INDEX_ACCESS_GET_FIELD_NAME "get"
Expand Down
9 changes: 9 additions & 0 deletions tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,15 @@ class CastLogicHelper
return in;
}

// a class value is its storage tuple, and the value of a base class is laid out as its subclass's
if (isa<mlir_ts::ClassValueType>(inType) || isa<mlir_ts::ClassValueType>(resType))
{
if (isa<mlir_ts::ClassValueType, mlir_ts::TupleType>(inType) && isa<mlir_ts::ClassValueType, mlir_ts::TupleType>(resType))
{
return in;
}
}

// a @value type is its storage tuple: the cast to or from that exact tuple changes nothing
// (MLIRGenImpl::valueStorage, and the cast that makes a tuple a value)
if (auto inValueType = dyn_cast<mlir_ts::ValueType>(inType); inValueType && inValueType.getStorageType() == resType)
Expand Down
18 changes: 18 additions & 0 deletions tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h
Original file line number Diff line number Diff line change
Expand Up @@ -1095,6 +1095,24 @@ struct ClassInfo
// static fields (a C++ vtable has none)
for (auto &staticField : isCppVTable ? llvm::MutableArrayRef<StaticFieldInfo>() : llvm::MutableArrayRef<StaticFieldInfo>(staticFields))
{
// a static field declared again, of the same type, takes over the base's slot, as a static
// method does: through a value of the base's class (`k: typeof A`) it is the field of the
// class `k` holds. The compiler's own (`.rtti`, `.size`) keep a slot each.
auto name = mlir::dyn_cast<mlir::StringAttr>(staticField.id);
if (name && !name.getValue().starts_with("."))
{
auto key = ("static " + name.getValue()).str();
auto it = methodSlots.find(key);
if (it != methodSlots.end() && vtable[it->second].staticFieldInfo.type == staticField.type)
{
staticField.virtualIndex = it->second;
vtable[it->second] = {staticField, false};
continue;
}

methodSlots[key] = vtable.size();
}

staticField.virtualIndex = vtable.size();
vtable.push_back({staticField, false});
}
Expand Down
4 changes: 4 additions & 0 deletions tslang/include/TypeScript/MLIRLogic/MLIRPrinter.h
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,10 @@ class MLIRPrinter

out << t.getName().getValue().str().c_str();
})
.template Case<mlir_ts::ClassValueType>([&](auto t) {
out << "typeof ";
printType(out, t.getClassType());
})
.template Case<mlir_ts::ClassStorageType>([&](auto t) {
printTupleType(out, t);
})
Expand Down
13 changes: 13 additions & 0 deletions tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,19 @@ class MLIRTypeHelper
// of a value - their types, sizes, what they own - sees the tuple. Anything else is unchanged.
// Sites that box or re-represent a tuple do not call this: a ValueType reaches them only as the
// tuple it is cast to (MLIRGenImpl::valueStorage), where a conversion of it is allowed.
// A class value's layout (ClassValueType): the class's vtable (null for an abstract class, which has
// none), the function that allocates an instance of it, its constructor (null for none), and its
// rtti, which tells one class from another, each an opaque pointer.
static mlir_ts::TupleType getClassValueStorageType(mlir::MLIRContext *context)
{
auto opaqueType = mlir_ts::OpaqueType::get(context);
return mlir_ts::TupleType::get(
context, {mlir_ts::FieldInfo{MLIRHelper::TupleFieldName(CLASS_VALUE_VTABLE_NAME, context), opaqueType, false, mlir_ts::AccessLevel::Public},
mlir_ts::FieldInfo{MLIRHelper::TupleFieldName(NEW_METHOD_NAME, context), opaqueType, false, mlir_ts::AccessLevel::Public},
mlir_ts::FieldInfo{MLIRHelper::TupleFieldName(CLASS_VALUE_CONSTRUCTOR_NAME, context), opaqueType, false, mlir_ts::AccessLevel::Public},
mlir_ts::FieldInfo{MLIRHelper::TupleFieldName(CLASS_VALUE_RTTI_NAME, context), opaqueType, false, mlir_ts::AccessLevel::Public}});
}

static mlir::Type stripValueType(mlir::Type type)
{
if (auto valueType = dyn_cast_or_null<mlir_ts::ValueType>(type))
Expand Down
6 changes: 6 additions & 0 deletions tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,12 @@ class TypeOfOpHelper
return "class";
}

// a class as a value is its constructor, as in JavaScript
if (isa<mlir_ts::ClassValueType>(type))
{
return "function";
}

if (isa<mlir_ts::ClassStorageType>(type))
{
return "class";
Expand Down
29 changes: 29 additions & 0 deletions tslang/include/TypeScript/TypeScriptTypes.td
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,35 @@ def TypeScript_Class : TypeScript_Type<"Class"> {
];
}

def TypeScript_ClassValue : TypeScript_Type<"ClassValue"> {
let mnemonic = "class_value";

let summary = "A class as a value: `typeof A`";
let description = [{
Syntax:

```
class-value-type ::= `class_value<` class-type `>`
```

A class given, stored or returned as a value: `A` itself or any class that extends it. Laid out as
its storage tuple, `{.vtable, .new, .constructor, .rtti}` - the class's vtable (null for an abstract
class), the function that allocates an instance of it, its constructor (null for none) and its rtti,
each an opaque pointer
(MLIRTypeHelper::getClassValueStorageType). `ts.Cast` to or from that tuple, or to the value of a
base class, lowers to nothing.
}];
let parameters = (ins "Type":$classType);

let assemblyFormat = "`<` params `>`";

let builders = [
TypeBuilderWithInferredContext<(ins "Type":$classType), [{
return Base::get(classType.getContext(), classType);
}]>
];
}

def TypeScript_Value : TypeScript_Type<"Value"> {
let mnemonic = "value";

Expand Down
6 changes: 6 additions & 0 deletions tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8636,6 +8636,12 @@ static void populateTypeScriptConversionPatterns(LLVMTypeConverter &converter, m
return converter.convertType(type.getStorageType());
});

// a class as a value: {vtable, .new, constructor, rtti}
converter.addConversion([&](mlir_ts::ClassValueType type) {
auto ptrType = LLVM::LLVMPointerType::get(m.getContext());
return LLVM::LLVMStructType::getLiteral(type.getContext(), {ptrType, ptrType, ptrType, ptrType}, TUPLE_TYPE_PACKED);
});

converter.addConversion([&](mlir_ts::BoundRefType type) {
SmallVector<mlir::Type> llvmStructType;
llvmStructType.push_back(LLVM::LLVMPointerType::get(m.getContext()));
Expand Down
41 changes: 41 additions & 0 deletions tslang/lib/TypeScript/MLIRGenAccessCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,41 @@ namespace mlirgen
classStorageType.getName().getValue(), name, true, argument, accessingFromLevel, genContext);
})
.Case<mlir_ts::ClassType>(classAccess)
// a class as a value (`k: typeof M`): its statics, through the vtable of whichever class it
// holds (ClassStaticFieldAccess reads VTABLE_NAME of it)
.Case<mlir_ts::ClassValueType>([&](auto classValueType) -> mlir::Value {
if (name == VTABLE_NAME)
{
return classValuePart(location, objectValue, 0);
}

auto classType = mlir::cast<mlir_ts::ClassType>(classValueType.getClassType());
auto classInfo = getClassInfoByFullName(classType.getName().getValue());
if (!classInfo)
{
return mlir::Value();
}

auto staticFieldIndex = classInfo->getStaticFieldIndex(MLIRHelper::TupleFieldName(name, builder.getContext()));
if (staticFieldIndex >= 0)
{
return ClassStaticFieldAccess(classInfo, location, objectValue, staticFieldIndex,
detectAccessLevel(classType, genContext), genContext);
}

// a static method has a vtable slot, which a subclass's static of that name takes
// over: through the value it is the static of the class the value holds
auto methodIndex = classInfo->getMethodIndex(name);
if (methodIndex >= 0 && classInfo->methods[methodIndex].isStatic)
{
return ClassMethodAccess(classInfo, location, objectValue, methodIndex, false,
detectAccessLevel(classType, genContext), genContext);
}

emitError(location) << "'" << name << "' through a value of '" << to_print(classValueType)
<< "': only a static member can be reached through a class value";
return mlir::Value();
})
.Case<mlir_ts::InterfaceType>([&](auto interfaceType) {
return InterfaceMembers(
location, objectValue, interfaceType.getName().getValue(), cl.getAttribute(),
Expand Down Expand Up @@ -2868,6 +2903,12 @@ namespace mlirgen
const GenContext &genContext)
{

// `new c(args)` with `c: typeof A`: whichever class `c` holds
if (isa<mlir_ts::ClassValueType>(value.getType()) && !suppressConstructorCall)
{
return NewClassInstanceFromClassValue(location, value, arguments, genContext);
}

auto type = value.getType();
type = mth.convertConstTupleTypeToTupleType(type);

Expand Down
7 changes: 7 additions & 0 deletions tslang/lib/TypeScript/MLIRGenCast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,13 @@ namespace mlirgen
LLVM_DEBUG(llvm::dbgs() << "\n!! cast " << valueType << "\n -> " << type
<< "\n";);

// a class given where its value is expected (`make(B)` for `c: typeof A`), or the value of a class
// where a base class's is: B's value is A's when B extends A
if (auto classValueType = dyn_cast<mlir_ts::ClassValueType>(type))
{
return castToClassValue(location, classValueType, value, genContext);
}

// A @value class is nominal. Its value seen as `any`, `unknown`, `Object` or an ordinary
// interface would be a boxed copy that has lost its class (no vtable to call its methods by);
// seen as another @value type, a value of a class it is not. With null or undefined it is
Expand Down
Loading
Loading