From a727f018516e3ba3b2c163e3ce7358a69002fb1d Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 18:30:30 +0000 Subject: [PATCH 1/5] Classes as values: `typeof A`, and `new c(args)` through it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `function make(c: typeof A, n: number) { return new c(n); } make(B, 1)` was "failed to legalize operation 'ts.ClassRef'": a class named only a class at compile time, and `new c(n)` built an `A` whatever `c` held. - `typeof A` of a class is a ClassValueType: a tuple of the class's vtable, its `.new`, its constructor and its rtti. No vtable layout changes. - A class becomes a value where a `typeof A` is expected. B is a value of `typeof A` when it extends A and its constructor takes A's parameters. - `new c(args)` calls `.new` through the value (an owned, fresh result) and then the constructor, when there is one. Too many arguments, or a value of an abstract class's type, is an error. - `==`/`!=` compare the rtti, `typeof` is "function", and a static field is read through the value's vtable; any other member through a value is an error. - A member of a class declared in a function that reads one of its locals is now an error naming the variable, instead of "Expected 1 arguments, but got 0". docs/classes-as-values-design.md §5 describes it and its limits. Co-Authored-By: Claude Opus 5.5 --- tslang/docs/classes-as-values-design.md | 48 +++- tslang/include/TypeScript/Defines.h | 4 + .../TypeScript/LowerToLLVM/CastLogicHelper.h | 9 + .../TypeScript/MLIRLogic/MLIRPrinter.h | 4 + .../TypeScript/MLIRLogic/MLIRTypeHelper.h | 13 + .../TypeScript/MLIRLogic/TypeOfOpHelper.h | 6 + tslang/include/TypeScript/TypeScriptTypes.td | 29 +++ tslang/lib/TypeScript/LowerToLLVM.cpp | 6 + tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 32 +++ tslang/lib/TypeScript/MLIRGenCast.cpp | 7 + tslang/lib/TypeScript/MLIRGenClasses.cpp | 235 ++++++++++++++++++ tslang/lib/TypeScript/MLIRGenFunctions.cpp | 18 ++ tslang/lib/TypeScript/MLIRGenImpl.h | 53 ++++ tslang/lib/TypeScript/MLIRGenTypes.cpp | 16 +- tslang/test/tester/CMakeLists.txt | 16 ++ tslang/test/tester/tests/00class_values.ts | 101 ++++++++ .../tester/tests/class_local_capture_error.ts | 18 ++ .../tests/class_value_constructor_error.ts | 16 ++ 18 files changed, 628 insertions(+), 3 deletions(-) create mode 100644 tslang/test/tester/tests/00class_values.ts create mode 100644 tslang/test/tester/tests/class_local_capture_error.ts create mode 100644 tslang/test/tester/tests/class_value_constructor_error.ts diff --git a/tslang/docs/classes-as-values-design.md b/tslang/docs/classes-as-values-design.md index 9ee2a690c..b0c9c6810 100644 --- a/tslang/docs/classes-as-values-design.md +++ b/tslang/docs/classes-as-values-design.md @@ -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 @@ -95,3 +96,48 @@ A local class used as a value (`return Counter`) carries its captures. Its value - `abstract new () => A` construct signatures and mixins (`function Mixin {}>(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` (`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, or null for an abstract class, which has none. +- **`.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). +- **Not yet:** a class from a declaration or another module, 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. Too many arguments is an error, and + so is a value of an abstract class's type. +- **`==` / `!=`:** compare the rtti; a class named beside a value is its value. +- **`typeof`** of a class value is `"function"`. +- **A static field** is read through the value's vtable (ADD_STATIC_MEMBERS_TO_VTABLE). A static that a + subclass declares again has a slot of its own, so the base's slot still reads the base's, as through + an instance. Any other member through a value (a static method) 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`, a static through the value; under + gc, rc, none and own. +- **`class_value_constructor_error`** and **`class_local_capture_error`:** the errors. diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 3084f5b9b..29bf2ee7e 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -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" diff --git a/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h b/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h index 3934ccd16..ef7eef20d 100644 --- a/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h +++ b/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h @@ -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(inType) || isa(resType)) + { + if (isa(inType) && isa(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(inType); inValueType && inValueType.getStorageType() == resType) diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRPrinter.h b/tslang/include/TypeScript/MLIRLogic/MLIRPrinter.h index d75c57036..ebbf0047e 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRPrinter.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRPrinter.h @@ -405,6 +405,10 @@ class MLIRPrinter out << t.getName().getValue().str().c_str(); }) + .template Case([&](auto t) { + out << "typeof "; + printType(out, t.getClassType()); + }) .template Case([&](auto t) { printTupleType(out, t); }) diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h index e1262db05..41fa414ec 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h @@ -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(type)) diff --git a/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h b/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h index 6c9e87bc2..e7735f479 100644 --- a/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h @@ -241,6 +241,12 @@ class TypeOfOpHelper return "class"; } + // a class as a value is its constructor, as in JavaScript + if (isa(type)) + { + return "function"; + } + if (isa(type)) { return "class"; diff --git a/tslang/include/TypeScript/TypeScriptTypes.td b/tslang/include/TypeScript/TypeScriptTypes.td index 36e3c0b8f..54c8dfef6 100644 --- a/tslang/include/TypeScript/TypeScriptTypes.td +++ b/tslang/include/TypeScript/TypeScriptTypes.td @@ -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"; diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 2bff8db12..2064d6243 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -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 llvmStructType; llvmStructType.push_back(LLVM::LLVMPointerType::get(m.getContext())); diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 4c1b74e44..5468c39e9 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -381,6 +381,32 @@ namespace mlirgen classStorageType.getName().getValue(), name, true, argument, accessingFromLevel, genContext); }) .Case(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([&](auto classValueType) -> mlir::Value { + if (name == VTABLE_NAME) + { + return classValuePart(location, objectValue, 0); + } + + auto classType = mlir::cast(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); + } + + emitError(location) << "'" << name << "' through a value of '" << to_print(classValueType) + << "': only a static field can be reached through a class value yet"; + return mlir::Value(); + }) .Case([&](auto interfaceType) { return InterfaceMembers( location, objectValue, interfaceType.getName().getValue(), cl.getAttribute(), @@ -2772,6 +2798,12 @@ namespace mlirgen const GenContext &genContext) { + // `new c(args)` with `c: typeof A`: whichever class `c` holds + if (isa(value.getType()) && !suppressConstructorCall) + { + return NewClassInstanceFromClassValue(location, value, arguments, genContext); + } + auto type = value.getType(); type = mth.convertConstTupleTypeToTupleType(type); diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 9ab561e33..c1424f5cb 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -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(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 diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index cb4009957..306b2cd6e 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -4215,5 +4215,240 @@ genContext); return mlir::success(); } + ValueOrLogicalResult MLIRGenImpl::mlirGenClassValue(mlir::Location location, mlir_ts::ClassType classType, + const GenContext &genContext) + { + auto classInfo = getClassInfoByFullName(classType.getName().getValue()); + if (!classInfo) + { + emitError(location) << "Can't find class " << to_print(classType); + return mlir::failure(); + } + + if (classInfo->isValue || classInfo->isDeclaration || classInfo->isImport || classInfo->isDynamicImport || + classInfo->isCppVTable) + { + emitError(location) << "class '" << classInfo->fullName << "' can't be used as a value yet"; + return mlir::failure(); + } + + auto opaqueType = getOpaqueType(); + auto nullOpaque = [&]() -> mlir::Value { + return builder.create(location, opaqueType, builder.create(location, getNullType())); + }; + auto functionAddress = [&](MethodInfo *methodInfo) -> mlir::Value { + if (!methodInfo) + { + return nullOpaque(); + } + + auto symbolRefOp = builder.create( + location, methodInfo->funcType, mlir::FlatSymbolRefAttr::get(builder.getContext(), methodInfo->funcName)); + return builder.create(location, opaqueType, symbolRefOp); + }; + + // the vtable, for a static read through the value; an abstract class has none + mlir::Value vtable; + if (classInfo->getHasVirtualTable() && !classInfo->isAbstract) + { + // as an instance gets it (mlirGenSetVTableToInstance) + auto vtableName = concat(classInfo->fullName, VTABLE_NAME); + if (auto vtableAddress = resolveFullNameIdentifier(location, vtableName, true, genContext)) + { + vtable = builder.create(location, opaqueType, vtableAddress); + } + else + { + vtable = builder.create(location, opaqueType, vtableName, ::mlir::IntegerAttr()); + } + } + else + { + vtable = nullOpaque(); + } + + // an abstract class has no `.new`: its value can't make an instance of it + auto newFunc = functionAddress(classInfo->isAbstract ? nullptr : classInfo->findMethod(NEW_METHOD_NAME)); + auto constructorFunc = functionAddress(classInfo->getHasConstructor() ? classInfo->findMethod(CONSTRUCTOR_NAME) : nullptr); + + // the rtti: every class has one, and no two the same + mlir::Value rtti; + auto rttiName = concat(classInfo->fullName, RTTI_NAME); + if (auto rttiAddress = resolveFullNameIdentifier(location, rttiName, true, genContext)) + { + rtti = builder.create(location, opaqueType, rttiAddress); + } + else + { + rtti = builder.create(location, opaqueType, rttiName, ::mlir::IntegerAttr()); + } + + auto storageType = MLIRTypeHelper::getClassValueStorageType(builder.getContext()); + auto storage = builder.create(location, storageType, + mlir::ValueRange{vtable, newFunc, constructorFunc, rtti}); + return V(builder.create(location, mlir_ts::ClassValueType::get(classType), storage)); + } + + ValueOrLogicalResult MLIRGenImpl::castToClassValue(mlir::Location location, mlir_ts::ClassValueType classValueType, + mlir::Value value, const GenContext &genContext) + { + auto baseClassType = mlir::cast(classValueType.getClassType()); + mlir_ts::ClassType classType; + mlir::Value classValue; + if (auto classRefOp = value.getDefiningOp()) + { + classType = classRefOp.getType(); + } + else if (auto valueClassValueType = dyn_cast(value.getType())) + { + classType = mlir::cast(valueClassValueType.getClassType()); + classValue = value; + } + else + { + emitError(location) << "'" << to_print(value.getType()) << "' is not a class, so it can't be a value of '" + << to_print(classValueType) << "'"; + return mlir::failure(); + } + + if (classType != baseClassType) + { + auto classInfo = getClassInfoByFullName(classType.getName().getValue()); + auto baseClassInfo = getClassInfoByFullName(baseClassType.getName().getValue()); + std::function extends = [&](ClassInfo::TypePtr derived) { + return llvm::any_of(derived->baseClasses, + [&](ClassInfo::TypePtr base) { return base == baseClassInfo || extends(base); }); + }; + if (!classInfo || !baseClassInfo || !extends(classInfo)) + { + emitError(location) << "class '" << to_print(classType) << "' does not extend '" << to_print(baseClassType) + << "', so it can't be a value of '" << to_print(classValueType) << "'"; + return mlir::failure(); + } + + // `new c(args)` passes what the base's constructor takes: the class's must take the same + auto parametersOf = [&](ClassInfo::TypePtr info) { + auto *constructorInfo = info->getHasConstructor() ? info->findMethod(CONSTRUCTOR_NAME) : nullptr; + return constructorInfo ? constructorInfo->funcType.getInputs().drop_front() : llvm::ArrayRef(); + }; + auto parameters = parametersOf(classInfo); + auto baseParameters = parametersOf(baseClassInfo); + if (parameters.size() > baseParameters.size() || + !std::equal(parameters.begin(), parameters.end(), baseParameters.begin())) + { + emitError(location) << "the constructor of class '" << to_print(classType) + << "' does not take the arguments the constructor of '" << to_print(baseClassType) + << "' does, so it can't be a value of '" << to_print(classValueType) << "'"; + return mlir::failure(); + } + } + + if (!classValue) + { + auto result = mlirGenClassValue(location, classType, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(result) + classValue = V(result); + } + + if (classValue.getType() == classValueType) + { + return classValue; + } + + // laid out the same: the base's value is the subclass's + return V(builder.create(location, classValueType, classValue)); + } + + mlir::Value MLIRGenImpl::classValuePart(mlir::Location location, mlir::Value classValue, int index) + { + auto storageType = MLIRTypeHelper::getClassValueStorageType(builder.getContext()); + auto storage = builder.create(location, storageType, classValue); + return builder.create(location, getOpaqueType(), storage, + builder.getDenseI64ArrayAttr({index})); + } + + ValueOrLogicalResult MLIRGenImpl::NewClassInstanceFromClassValue(mlir::Location location, mlir::Value classValue, + NodeArray arguments, + const GenContext &genContext) + { + auto classType = mlir::cast(mlir::cast(classValue.getType()).getClassType()); + auto classInfo = getClassInfoByFullName(classType.getName().getValue()); + if (!classInfo) + { + emitError(location) << "Can't find class " << to_print(classType); + return mlir::failure(); + } + + if (classInfo->isAbstract) + { + emitError(location) << "Cannot create an instance of an abstract class through a value of '" + << to_print(classValue.getType()) << "'"; + return mlir::failure(); + } + + // the arguments, for the constructor the class itself has: a class whose value this can be + // extends it, and takes what its constructor takes (castToClassValue) + auto *constructorInfo = classInfo->getHasConstructor() ? classInfo->findMethod(CONSTRUCTOR_NAME) : nullptr; + auto parameterCount = constructorInfo ? constructorInfo->funcType.getNumInputs() - 1 : 0; + if (arguments.size() > parameterCount) + { + emitError(location) << "Expected " << parameterCount << " arguments, but got " << arguments.size(); + return mlir::failure(); + } + + SmallVector operands; + if (constructorInfo) + { + if (mlir::failed(mlirGenOperands(arguments, operands, constructorInfo->funcType, genContext, 1/*this params shift*/))) + { + emitError(location) << "Call constructor: can't resolve values of all parameters"; + return mlir::failure(); + } + } + + // allocate: the class's own `.new`, which sets its vtable + auto newFuncType = getFunctionType({}, {classType}, false); + auto newFunc = builder.create(location, newFuncType, classValuePart(location, classValue, 1)); + auto callNewOp = builder.create(location, newFunc, mlir::ValueRange{}); + callNewOp->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + callNewOp->setAttr(OWN_FRESH_RESULT_ATTR_NAME, builder.getUnitAttr()); + auto instance = callNewOp.getResult(0); + + // construct: its constructor, when it has one + auto constructorPart = classValuePart(location, classValue, 2); + CAST_A(hasConstructor, location, getBooleanType(), constructorPart, genContext); + // the instance first, as a method's `this` (which the call borrows), then each argument as its + // parameter's type; one left out for an optional parameter is undefined + auto constructorFuncType = constructorInfo ? constructorInfo->funcType : getFunctionType({classType}, {}, false); + SmallVector callOperands{instance}; + for (auto index = 0u; index < parameterCount; index++) + { + auto parameterType = constructorFuncType.getInput(index + 1); + if (index < operands.size()) + { + CAST_A(argument, location, parameterType, operands[index], genContext); + callOperands.push_back(argument); + } + else if (isa(parameterType)) + { + callOperands.push_back(builder.create(location, parameterType)); + } + else + { + emitError(location) << "Expected " << parameterCount << " arguments, but got " << operands.size(); + return mlir::failure(); + } + } + + builder.create( + location, hasConstructor, [&](mlir::OpBuilder &opBuilder, mlir::Location loc) { + auto constructorFunc = builder.create(location, constructorFuncType, constructorPart); + builder.create(location, constructorFunc, callOperands); + builder.create(loc); + }); + + return instance; + } + } // namespace mlirgen } // namespace typescript diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 7bb217ab8..430b879ac 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -874,6 +874,24 @@ namespace mlirgen << "\n!! ret type: " << funcProto->getReturnType() << ", name: " << name << "\n";); } + // a member of a class declared in a function, reading that function's locals: nothing passes + // them to it - a call through the object, or `new`, has no captures to give - so it is an + // error, not a call with an argument missing (docs/classes-as-values-design.md §3) + auto kind = (SyntaxKind)functionLikeDeclarationBaseAST; + if (passResult->outerVariables.size() > 0 && genContext.thisType && + isa(genContext.thisType) && + (kind == SyntaxKind::MethodDeclaration || kind == SyntaxKind::Constructor || + kind == SyntaxKind::GetAccessor || kind == SyntaxKind::SetAccessor)) + { + std::string captured = passResult->outerVariables.begin()->getKey().str(); + auto classInfo = getClassInfoByFullName(mlir::cast(genContext.thisType).getName().getValue()); + std::string className = classInfo ? classInfo->name.str() : to_print(genContext.thisType); + emitError(loc(functionLikeDeclarationBaseAST)) + << "a member of class '" << className.c_str() << "' reads '" << captured.c_str() + << "', a local of the function the class is declared in: a class can't capture yet"; + return mlir::failure(); + } + // if we have captured parameters, add first param to send lambda's type(class) if (passResult->outerVariables.size() > 0) { diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index bd8c41c3c..6a0c91854 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -8353,6 +8353,45 @@ class MLIRGenImpl case SyntaxKind::EqualsEqualsEqualsToken: case SyntaxKind::ExclamationEqualsToken: case SyntaxKind::ExclamationEqualsEqualsToken: + // two class values are the same class: the same rtti. A class named beside one (`k == A`) is + // its value + if (auto leftClassValueType = dyn_cast(leftExpressionValue.getType()); + leftClassValueType && rightExpressionValue.getDefiningOp()) + { + auto classValue = mlirGenClassValue(location, rightExpressionValue.getDefiningOp().getType(), genContext); + if (classValue.failed_or_no_value()) + { + return mlir::Value(); + } + + rightExpressionValue = V(classValue); + } + else if (auto rightClassValueType = dyn_cast(rightExpressionValue.getType()); + rightClassValueType && leftExpressionValue.getDefiningOp()) + { + auto classValue = mlirGenClassValue(location, leftExpressionValue.getDefiningOp().getType(), genContext); + if (classValue.failed_or_no_value()) + { + return mlir::Value(); + } + + leftExpressionValue = V(classValue); + } + + if (isa(leftExpressionValue.getType()) && + isa(rightExpressionValue.getType())) + { + result = builder.create(location, getBooleanType(), + builder.getI32IntegerAttr((int)opCode), + classValuePart(location, leftExpressionValue, 3), + classValuePart(location, rightExpressionValue, 3)); + break; + } + + result = builder.create(location, getBooleanType(), + builder.getI32IntegerAttr((int)opCode), + leftExpressionValue, rightExpressionValue); + break; case SyntaxKind::GreaterThanToken: case SyntaxKind::GreaterThanEqualsToken: case SyntaxKind::LessThanToken: @@ -14882,6 +14921,20 @@ class MLIRGenImpl mlir::Type OmitTypes(mlir::Type type, mlir::Type keys); mlir::Type getTypeByTypeQuery(TypeQueryNode typeQueryAST, const GenContext &genContext); + // the type `typeof` gives the value an expression evaluated to: a class's value for a class + mlir::Type typeOfQueried(mlir::Value value); + + // ---- Classes as values (docs/classes-as-values-design.md) ---- + // `A` as a value of `typeof A`: its vtable, its `.new` and its constructor + ValueOrLogicalResult mlirGenClassValue(mlir::Location location, mlir_ts::ClassType classType, const GenContext &genContext); + // `B` (a class reference) or a value of `typeof B` as a value of `typeof A`, for B extending A + ValueOrLogicalResult castToClassValue(mlir::Location location, mlir_ts::ClassValueType classValueType, mlir::Value value, + const GenContext &genContext); + // the `index`th of a class value's {vtable, .new, constructor}, an opaque pointer + mlir::Value classValuePart(mlir::Location location, mlir::Value classValue, int index); + // `new c(args)` for `c: typeof A`: `.new` through the value, then its constructor + ValueOrLogicalResult NewClassInstanceFromClassValue(mlir::Location location, mlir::Value classValue, + NodeArray arguments, const GenContext &genContext); mlir::Type getTypePredicateType(TypePredicateNode typePredicateNode, const GenContext &genContext); diff --git a/tslang/lib/TypeScript/MLIRGenTypes.cpp b/tslang/lib/TypeScript/MLIRGenTypes.cpp index f4fb74dc9..4d2427dd9 100644 --- a/tslang/lib/TypeScript/MLIRGenTypes.cpp +++ b/tslang/lib/TypeScript/MLIRGenTypes.cpp @@ -1667,13 +1667,25 @@ namespace mlirgen } auto val = V(result); - return val.getType(); + return typeOfQueried(val); } - auto type = evaluate(exprName.as(), genContext); + mlir::Type type; + evaluate(exprName.as(), [&](mlir::Value val) { type = typeOfQueried(val); }, genContext); return type; } + mlir::Type MLIRGenImpl::typeOfQueried(mlir::Value value) + { + // `typeof A` of a class is the class as a value, not an instance of it + if (auto classRefOp = value.getDefiningOp()) + { + return mlir_ts::ClassValueType::get(classRefOp.getType()); + } + + return value.getType(); + } + mlir::Type MLIRGenImpl::getTypePredicateType(TypePredicateNode typePredicateNode, const GenContext &genContext) { auto type = getType(typePredicateNode->type, genContext); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 138d7d5ff..dd3f72382 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -741,6 +741,7 @@ tslang_add_test(NAME test-compile-00-try-finally-throws COMMAND test-runner "${P tslang_add_test(NAME test-compile-00-function-fewer-parameters COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00function_fewer_parameters.ts") tslang_add_test(NAME test-compile-00-closure-fewer-parameters COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00closure_fewer_parameters.ts") tslang_add_test(NAME test-compile-00-in-interface-union COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00in_interface_union.ts") +tslang_add_test(NAME test-compile-00-class-values COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_values.ts") tslang_add_test(NAME test-compile-00-interface-union-literal COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_union_literal.ts") tslang_add_test(NAME test-compile-01-try-finally COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/01try_finally.ts") tslang_add_test(NAME test-compile-00-try-finally-return COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_return.ts") @@ -1371,6 +1372,7 @@ tslang_add_test(NAME test-jit-00-try-finally-throws COMMAND test-runner -jit "${ tslang_add_test(NAME test-jit-00-function-fewer-parameters COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00function_fewer_parameters.ts") tslang_add_test(NAME test-jit-00-closure-fewer-parameters COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00closure_fewer_parameters.ts") tslang_add_test(NAME test-jit-00-in-interface-union COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00in_interface_union.ts") +tslang_add_test(NAME test-jit-00-class-values COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_values.ts") tslang_add_test(NAME test-jit-00-interface-union-literal COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_union_literal.ts") tslang_add_test(NAME test-jit-01-try-finally COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/01try_finally.ts") tslang_add_test(NAME test-jit-00-try-finally-return COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_return.ts") @@ -1679,6 +1681,20 @@ add_test(NAME test-compile-shared-import-unresolved-iface COMMAND test-runner -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_unresolved_iface.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_unresolved_iface.ts") set_tests_properties(test-compile-shared-import-unresolved-iface PROPERTIES PASS_REGULAR_EXPRESSION "error: can't find type by name: Hidden" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +# Classes as values under every memory model (00class_values runs under gc above) +foreach(class_value_mm rc none own) + tslang_add_test(NAME test-jit-00-class-values-${class_value_mm} COMMAND test-runner -jit -mm=${class_value_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_values.ts") +endforeach() +# ...a class whose constructor takes other arguments than its base's is no value of the base's type +add_test(NAME test-compile-class-value-constructor-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/class_value_constructor_error.ts") +set_tests_properties(test-compile-class-value-constructor-error PROPERTIES PASS_REGULAR_EXPRESSION "the constructor of class 'Named' does not take the arguments the constructor of 'Base' does" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +# ...and a local class's member reading the function's locals is an error naming the variable +add_test(NAME test-compile-class-local-capture-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/class_local_capture_error.ts") +set_tests_properties(test-compile-class-local-capture-error PROPERTIES PASS_REGULAR_EXPRESSION "a member of class 'Counter' reads 'start', a local of the function the class is declared in" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") # @keeps and @borrows across the boundary: the importer reads them from __decls (-mm=own), and the # other models ignore them foreach(markers_mm gc rc own) diff --git a/tslang/test/tester/tests/00class_values.ts b/tslang/test/tester/tests/00class_values.ts new file mode 100644 index 000000000..50fafd4fc --- /dev/null +++ b/tslang/test/tester/tests/00class_values.ts @@ -0,0 +1,101 @@ +// A class as a value (`typeof A`): given, stored, put in an array, returned, held in a field, compared, +// and `new`-ed through - whichever class it holds is the one constructed, with its own constructor, +// field initializers and methods. +class Shape { + name = "shape"; + + constructor(public s: number) {} + + area() { + return 0; + } +} + +class Square extends Shape { + constructor(s: number) { + super(s); + this.name = "square"; + } + + area() { + return this.s * this.s; + } +} + +// no constructor of its own: Shape's +class Triple extends Shape { + area() { + return 3 * this.s * this.s; + } +} + +class Plain { + v = 5; +} + +abstract class Base {} +class Impl extends Base {} + +class Holder { + constructor(public kind: typeof Shape) {} +} + +class Counter { + static count = 7; +} + +function make(c: typeof Shape, s: number) { + return new c(s); +} + +function pick(i: number): typeof Shape { + if (i == 0) return Square; + if (i == 1) return Triple; + return Shape; +} + +function countOf(k: typeof Counter) { + return k.count; +} + +function main() { + assert(make(Square, 3).area() == 9, "factory, subclass"); + assert(make(Shape, 3).area() == 0, "factory, the class itself"); + assert(make(Square, 3).name == "square" && make(Triple, 3).name == "shape", "constructors and initializers"); + + const kinds: (typeof Shape)[] = [Square, Triple, Shape]; + let total: number = 0; + for (const k of kinds) { + total += new k(2).area(); + } + + assert(total == 4 + 12, "array of classes"); + + let c = pick(1); + assert(new c(1).area() == 3, "returned"); + c = pick(0); + assert(new c(5).area() == 25, "assigned"); + + const h = new Holder(Square); + assert(new h.kind(4).area() == 16, "field"); + + const p: typeof Plain = Plain; + assert(new p().v == 5, "no constructor"); + + assert(new (pick(0))(4) instanceof Square, "instanceof the instance"); + + const a: typeof Shape = Square; + const b: typeof Shape = Square; + const t: typeof Shape = Triple; + assert(a == b && a != t && !(a === t), "equality"); + + const x: typeof Base = Impl; + const y: typeof Base = Base; + assert(x != y && y == Base, "abstract classes"); + + assert(typeof a == "function", "typeof"); + + assert(countOf(Counter) == 7, "static through the value"); + + print("done."); +} diff --git a/tslang/test/tester/tests/class_local_capture_error.ts b/tslang/test/tester/tests/class_local_capture_error.ts new file mode 100644 index 000000000..58b6f09c5 --- /dev/null +++ b/tslang/test/tester/tests/class_local_capture_error.ts @@ -0,0 +1,18 @@ +// A member of a class declared in a function reads one of its locals: nothing would pass it to the +// member, so it is an error naming the variable (docs/classes-as-values-design.md §3). +function counter(start: number) { + class Counter { + n = 0; + + inc() { + this.n += start; + return this.n; + } + } + + return new Counter(); +} + +function main() { + print(counter(2).inc()); +} diff --git a/tslang/test/tester/tests/class_value_constructor_error.ts b/tslang/test/tester/tests/class_value_constructor_error.ts new file mode 100644 index 000000000..178e69d44 --- /dev/null +++ b/tslang/test/tester/tests/class_value_constructor_error.ts @@ -0,0 +1,16 @@ +// A class whose constructor takes other arguments than its base's is no value of `typeof Base`: +// `new k(1)` would give it a number for its string. +class Base { + constructor(public n: number) {} +} + +class Named extends Base { + constructor(public s: string) { + super(0); + } +} + +function main() { + const k: typeof Base = Named; + print(new k(1).n); +} From 37ca85c449d224c38b61c5425552e81e88c9292c Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 18:54:54 +0000 Subject: [PATCH 2/5] Class values: `new c(...spread)` and a rest constructor; verifier skips the error tests - `new c(args)` through a class value now calls the constructor with mlirGenCallFunction, so a spread argument and a rest parameter are handled as in any call (newWithSpread.ts was "Expected 3 arguments, but got 4"). - newWithSpread.ts read `c` and `g` without setting them: that only worked while `typeof B` was B at compile time. They are initialized now. - verify-ownership.cmake skips class_value_constructor_error.ts and class_local_capture_error.ts, which are errors by design. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenClasses.cpp | 38 +++++++---------------- tslang/test/tester/tests/newWithSpread.ts | 4 +-- tslang/test/tester/verify-ownership.cmake | 5 ++- 3 files changed, 18 insertions(+), 29 deletions(-) diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index 2e5780045..b702df01d 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -4483,10 +4483,9 @@ genContext); // the arguments, for the constructor the class itself has: a class whose value this can be // extends it, and takes what its constructor takes (castToClassValue) auto *constructorInfo = classInfo->getHasConstructor() ? classInfo->findMethod(CONSTRUCTOR_NAME) : nullptr; - auto parameterCount = constructorInfo ? constructorInfo->funcType.getNumInputs() - 1 : 0; - if (arguments.size() > parameterCount) + if (!constructorInfo && arguments.size() > 0) { - emitError(location) << "Expected " << parameterCount << " arguments, but got " << arguments.size(); + emitError(location) << "Expected 0 arguments, but got " << arguments.size(); return mlir::failure(); } @@ -4511,35 +4510,22 @@ genContext); // construct: its constructor, when it has one auto constructorPart = classValuePart(location, classValue, 2); CAST_A(hasConstructor, location, getBooleanType(), constructorPart, genContext); - // the instance first, as a method's `this` (which the call borrows), then each argument as its - // parameter's type; one left out for an optional parameter is undefined + // the instance first, as a method's `this` (which the call borrows), then the arguments as a + // call of the constructor takes them: cast to its parameters, optional ones left out undefined, + // a rest parameter packed into its array auto constructorFuncType = constructorInfo ? constructorInfo->funcType : getFunctionType({classType}, {}, false); - SmallVector callOperands{instance}; - for (auto index = 0u; index < parameterCount; index++) - { - auto parameterType = constructorFuncType.getInput(index + 1); - if (index < operands.size()) - { - CAST_A(argument, location, parameterType, operands[index], genContext); - callOperands.push_back(argument); - } - else if (isa(parameterType)) - { - callOperands.push_back(builder.create(location, parameterType)); - } - else - { - emitError(location) << "Expected " << parameterCount << " arguments, but got " << operands.size(); - return mlir::failure(); - } - } - + auto failed = false; builder.create( location, hasConstructor, [&](mlir::OpBuilder &opBuilder, mlir::Location loc) { auto constructorFunc = builder.create(location, constructorFuncType, constructorPart); - builder.create(location, constructorFunc, callOperands); + auto result = mlirGenCallFunction(location, constructorFuncType, constructorFunc, instance, operands, genContext); + failed = mlir::failed(result); builder.create(loc); }); + if (failed) + { + return mlir::failure(); + } return instance; } diff --git a/tslang/test/tester/tests/newWithSpread.ts b/tslang/test/tester/tests/newWithSpread.ts index 6abd17a71..e47e4aaca 100644 --- a/tslang/test/tester/tests/newWithSpread.ts +++ b/tslang/test/tester/tests/newWithSpread.ts @@ -32,9 +32,9 @@ function main() { const b2 = new weakB(1, 2, ...a, "string"); let b: A = { f: B }; - let c: C; + let c: C = { "a-b": B }; let d: A[] = [b, b]; - let g: C[]; + let g: C[] = [c, c]; // Property access expression new b.f(1, 2, "string"); diff --git a/tslang/test/tester/verify-ownership.cmake b/tslang/test/tester/verify-ownership.cmake index 5d2202579..5650469df 100644 --- a/tslang/test/tester/verify-ownership.cmake +++ b/tslang/test/tester/verify-ownership.cmake @@ -48,7 +48,10 @@ set(not_compilable_alone import_final_extends.ts # an error by design: an object literal for an imported @value class # (test-compile-shared-import-value-types-structural) - import_value_types_structural.ts) + import_value_types_structural.ts + # errors by design (test-compile-class-value-constructor-error, test-compile-class-local-capture-error) + class_value_constructor_error.ts + class_local_capture_error.ts) file(GLOB corpus "${TESTS_DIR}/*.ts") list(SORT corpus) From c9e2f4344ee90115f879be9fe500937a4891b8bb Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 19:14:54 +0000 Subject: [PATCH 3/5] Class values: static methods through the value; an abstract class's statics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `c.label()` through a `typeof Unit` value calls the static of the class `c` holds: a subclass's static method of the same name takes over the vtable slot (ClassMethodAccess). Before, any member but a static field was an error. - An abstract class gets a vtable too, though no instance carries it: a value holding the abstract class itself read a static field (now a method too) through a null vtable and crashed. Its abstract methods' and interfaces' slots are null. - 00class_values covers static methods (a subclass's, an inherited one, with arguments) and an abstract class's own statics; the design doc §5 says so. Co-Authored-By: Claude Opus 5.5 --- tslang/docs/classes-as-values-design.md | 18 +++--- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 11 +++- tslang/lib/TypeScript/MLIRGenClasses.cpp | 40 ++++++++----- tslang/test/tester/tests/00class_values.ts | 66 +++++++++++++++++++++ 4 files changed, 113 insertions(+), 22 deletions(-) diff --git a/tslang/docs/classes-as-values-design.md b/tslang/docs/classes-as-values-design.md index b0c9c6810..6697220b1 100644 --- a/tslang/docs/classes-as-values-design.md +++ b/tslang/docs/classes-as-values-design.md @@ -102,7 +102,8 @@ A local class used as a value (`return Counter`) carries its captures. Its value **The value.** `ClassValueType` (`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, or null for an abstract class, which has none. +- **`.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. @@ -120,13 +121,15 @@ between the value and that tuple, or to the value of a base class, lowers to not **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. Too many arguments is an error, and - so is a value of an abstract class's type. + 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 field** is read through the value's vtable (ADD_STATIC_MEMBERS_TO_VTABLE). A static that a - subclass declares again has a slot of its own, so the base's slot still reads the base's, as through - an instance. Any other member through a value (a static method) is an error. +- **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. A static field that a subclass declares again has a + slot of its own, so the base's slot still reads the base's, as through an instance. +- 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. @@ -138,6 +141,7 @@ region"): the initializers reach the implicit constructor after captures are fou **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`, a static through the value; under + 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. - **`class_value_constructor_error`** and **`class_local_capture_error`:** the errors. diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index a563b478d..b2525d4ce 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -403,8 +403,17 @@ namespace mlirgen 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 field can be reached through a class value yet"; + << "': only a static member can be reached through a class value"; return mlir::Value(); }) .Case([&](auto interfaceType) { diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index b702df01d..d0e92298a 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -3650,11 +3650,22 @@ genContext); mlir::LogicalResult MLIRGenImpl::mlirGenClassVirtualTableDefinition(mlir::Location location, ClassInfo::TypePtr newClassPtr, const GenContext &genContext) { - if (!newClassPtr->getHasVirtualTable() || newClassPtr->isAbstract) + // an abstract class has one too, though no instance carries it: a value of the class + // (`const k: typeof A = A`) reads its static members through it. Its abstract methods' + // and its interfaces' slots are null, as only a static is read through it. + if (!newClassPtr->getHasVirtualTable()) { return mlir::success(); } - + + auto nullSlot = [&](mlir::Location location, mlir::Type slotType) -> mlir::Value { + // through Opaque: a null function is no TypeScript value + auto nullValue = builder.create(location, getNullType()); + auto nullOpaque = builder.create(location, getOpaqueType(), nullValue); + auto castResult = cast(location, slotType, nullOpaque, genContext); + return castResult.failed_or_no_value() ? mlir::Value() : V(castResult); + }; + // TODO: ... llvm::SmallVector virtualTable; newClassPtr->getVirtualTable(virtualTable); @@ -3688,7 +3699,13 @@ genContext); auto fieldIndex = 0; for (auto vtRecord : virtualTable) { - if (vtRecord.isInterfaceVTable) + if (vtRecord.isInterfaceVTable && newClassPtr->isAbstract) + { + vtableValue = builder.create( + location, virtTuple, nullSlot(location, getOpaqueType()), vtableValue, + MLIRHelper::getStructIndex(builder, fieldIndex++)); + } + else if (vtRecord.isInterfaceVTable) { // TODO: write correct full name for vtable auto fullClassInterfaceVTableFieldName = @@ -3751,7 +3768,7 @@ genContext); mlir::Type slotType; if (!vtRecord.isStaticField) { - if (vtRecord.methodInfo.isAbstract) + if (vtRecord.methodInfo.isAbstract && !newClassPtr->isAbstract) { emitError(location) << "Abstract method '" << vtRecord.methodInfo.name << "' is not implemented in '" << newClassPtr->name << "'"; return TypeValueInitType{mlir::Type(), mlir::Value(), TypeProvided::No}; @@ -3808,18 +3825,13 @@ genContext); return owner && owner->isCppVTable && !owner->isCppVTableImplementation; }; - if (isUnimplementedCppMethod()) + if (isUnimplementedCppMethod() || (!vtRecord.isStaticField && vtRecord.methodInfo.isAbstract)) { - // through Opaque: a null function is no TypeScript value - auto nullValue = builder.create(location, getNullType()); - auto nullOpaque = builder.create(location, getOpaqueType(), nullValue); - auto castResult = cast(location, slotType, nullOpaque, genContext); - if (castResult.failed_or_no_value()) + methodOrFieldNameRef = nullSlot(location, slotType); + if (!methodOrFieldNameRef) { return TypeValueInitType{mlir::Type(), mlir::Value(), TypeProvided::No}; } - - methodOrFieldNameRef = V(castResult); } else if (isOwnedByDynamicImport(symbolName, vtRecord.isStaticField)) { @@ -4341,9 +4353,9 @@ genContext); return builder.create(location, opaqueType, symbolRefOp); }; - // the vtable, for a static read through the value; an abstract class has none + // the vtable, for a static read through the value (an abstract class has one for that) mlir::Value vtable; - if (classInfo->getHasVirtualTable() && !classInfo->isAbstract) + if (classInfo->getHasVirtualTable()) { // as an instance gets it (mlirGenSetVTableToInstance) auto vtableName = concat(classInfo->fullName, VTABLE_NAME); diff --git a/tslang/test/tester/tests/00class_values.ts b/tslang/test/tester/tests/00class_values.ts index 50fafd4fc..2d2123b7e 100644 --- a/tslang/test/tester/tests/00class_values.ts +++ b/tslang/test/tester/tests/00class_values.ts @@ -44,6 +44,54 @@ class Counter { static count = 7; } +// statics through a value: a subclass's static of the same name is the one called +class Unit { + static label() { + return "unit"; + } + + static scaled(k: number) { + return k; + } +} + +class Double extends Unit { + static label() { + return "double"; + } + + static scaled(k: number) { + return 2 * k; + } +} + +class Inherits extends Unit {} + +interface Named { + title(): string; +} + +// an abstract class's own value: its vtable has its statics, its abstract and interface slots null +abstract class Kind implements Named { + static n = 4; + + static id() { + return 1; + } + + abstract title(): string; +} + +class Concrete extends Kind { + static id() { + return 2; + } + + title() { + return "concrete"; + } +} + function make(c: typeof Shape, s: number) { return new c(s); } @@ -58,6 +106,10 @@ function countOf(k: typeof Counter) { return k.count; } +function labelOf(u: typeof Unit) { + return u.label(); +} + function main() { assert(make(Square, 3).area() == 9, "factory, subclass"); assert(make(Shape, 3).area() == 0, "factory, the class itself"); @@ -97,5 +149,19 @@ function main() { assert(countOf(Counter) == 7, "static through the value"); + assert(labelOf(Double) == "double" && labelOf(Unit) == "unit" && labelOf(Inherits) == "unit", "static methods"); + const units: (typeof Unit)[] = [Double, Inherits]; + let scaled: number = 0; + for (const u of units) { + scaled += u.scaled(3); + } + + assert(scaled == 9, "static method with arguments"); + + const kind: typeof Kind = Kind; + const concrete: typeof Kind = Concrete; + assert(kind.id() == 1 && kind.n == 4 && concrete.id() == 2 && concrete.n == 4, "statics of an abstract class's value"); + assert(new Concrete().title() == "concrete", "abstract slot filled"); + print("done."); } From 1e88a2d61a32721d663cf6741b8b6a673654b970 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 19:38:12 +0000 Subject: [PATCH 4/5] Class values: a static field declared again takes over the base's slot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `k.count` through a `typeof Counter` value holding `Recount` read Counter's count: a subclass's static field of the same name got a vtable slot of its own. Now one of the same type takes over the base's slot, as a static method does, so it is the field of the class the value holds. The compiler's own statics (`.rtti`, `.size`) keep a slot each. 00class_values covers it; the design doc §5 says so. Co-Authored-By: Claude Opus 5.5 --- tslang/docs/classes-as-values-design.md | 5 +++-- .../TypeScript/MLIRLogic/MLIRGenStore.h | 18 ++++++++++++++++++ tslang/test/tester/tests/00class_values.ts | 10 ++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/tslang/docs/classes-as-values-design.md b/tslang/docs/classes-as-values-design.md index 6697220b1..862d93989 100644 --- a/tslang/docs/classes-as-values-design.md +++ b/tslang/docs/classes-as-values-design.md @@ -127,8 +127,9 @@ between the value and that tuple, or to the value of a base class, lowers to not - **`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. A static field that a subclass declares again has a - slot of its own, so the base's slot still reads the base's, as through an instance. +- **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 diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index 933cec3b0..575c3783d 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -1095,6 +1095,24 @@ struct ClassInfo // static fields (a C++ vtable has none) for (auto &staticField : isCppVTable ? llvm::MutableArrayRef() : llvm::MutableArrayRef(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(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}); } diff --git a/tslang/test/tester/tests/00class_values.ts b/tslang/test/tester/tests/00class_values.ts index 2d2123b7e..abedaa9cc 100644 --- a/tslang/test/tester/tests/00class_values.ts +++ b/tslang/test/tester/tests/00class_values.ts @@ -44,6 +44,13 @@ class Counter { static count = 7; } +// declared again: through a value of Counter's type, the field of the class the value holds +class Recount extends Counter { + static count = 8; +} + +class Uncounted extends Counter {} + // statics through a value: a subclass's static of the same name is the one called class Unit { static label() { @@ -148,6 +155,9 @@ function main() { assert(typeof a == "function", "typeof"); assert(countOf(Counter) == 7, "static through the value"); + assert(countOf(Recount) == 8 && countOf(Uncounted) == 7, "static declared again"); + Recount.count = 9; + assert(countOf(Recount) == 9 && Counter.count == 7, "static declared again, written"); assert(labelOf(Double) == "double" && labelOf(Unit) == "unit" && labelOf(Inherits) == "unit", "static methods"); const units: (typeof Unit)[] = [Double, Inherits]; From e5f615039557c3a62f3a0b170698c2b1d1c9660c Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 20:03:00 +0000 Subject: [PATCH 5/5] Class values: another module's classes, a shared library's too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `const c: typeof K.Shape = K.Square` with K from another module was "class 'K.Square' can't be used as a value yet". - A linked module's class: the check is lifted; its symbols are linked as any. - A shared library's (-shared): `.new`, the constructor and the rtti are read through the pointers the importer resolves at load time, and the 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 constructor through that pointer, not as a function of that name (it crashed). - A library class's static field read through a vtable is the field the slot points at, not the importer's pointer to it (it crashed). - import_class_values + export_class_values: linked, -shared, -jit -shared, and -jit -shared under rc, none and own. The design doc §5 says so. Co-Authored-By: Claude Opus 5.5 --- tslang/docs/classes-as-values-design.md | 9 ++- tslang/lib/TypeScript/MLIRGenClasses.cpp | 58 +++++++++++++++++-- tslang/lib/TypeScript/MLIRGenImpl.h | 16 ++++- tslang/test/tester/CMakeLists.txt | 5 ++ .../test/tester/tests/export_class_values.ts | 44 ++++++++++++++ .../test/tester/tests/import_class_values.ts | 35 +++++++++++ 6 files changed, 160 insertions(+), 7 deletions(-) create mode 100644 tslang/test/tester/tests/export_class_values.ts create mode 100644 tslang/test/tester/tests/import_class_values.ts diff --git a/tslang/docs/classes-as-values-design.md b/tslang/docs/classes-as-values-design.md index 862d93989..4feff58c0 100644 --- a/tslang/docs/classes-as-values-design.md +++ b/tslang/docs/classes-as-values-design.md @@ -116,7 +116,12 @@ between the value and that tuple, or to the value of a base class, lowers to not 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). -- **Not yet:** a class from a declaration or another module, a @value class or a @cpp class can't be a value. +- **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 @@ -145,4 +150,6 @@ region"): the initializers reach the implicit constructor after captures are fou 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. diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index d0e92298a..a3422b0a5 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -4331,8 +4331,7 @@ genContext); return mlir::failure(); } - if (classInfo->isValue || classInfo->isDeclaration || classInfo->isImport || classInfo->isDynamicImport || - classInfo->isCppVTable) + if (classInfo->isValue || classInfo->isCppVTable) { emitError(location) << "class '" << classInfo->fullName << "' can't be used as a value yet"; return mlir::failure(); @@ -4342,12 +4341,45 @@ genContext); auto nullOpaque = [&]() -> mlir::Value { return builder.create(location, opaqueType, builder.create(location, getNullType())); }; + // a class of a shared library (-shared) has its functions and its rtti behind pointers the + // importer resolves at load time (mlirGenClassMethodMemberDynamicImport, + // mlirGenCustomRTTIDynamicImport): the value is read through them + auto loadedOpaque = [&](mlir::StringRef name) -> mlir::Value { + auto value = resolveFullNameIdentifier(location, name, false, genContext); + if (!value) + { + return mlir::Value(); + } + + if (auto refType = dyn_cast(value.getType())) + { + value = builder.create(location, refType.getElementType(), value); + } + + return builder.create(location, opaqueType, value); + }; auto functionAddress = [&](MethodInfo *methodInfo) -> mlir::Value { if (!methodInfo) { return nullOpaque(); } + // the class that has the method: a class without a constructor of its own has its base's, + // which may be a shared library's + std::function ownedByDynamicImport = [&](ClassInfo::TypePtr cls) -> bool { + if (llvm::any_of(cls->methods, [&](auto &m) { return m.funcName == methodInfo->funcName; })) + { + return cls->isDynamicImport; + } + + return llvm::any_of(cls->baseClasses, [&](auto &base) { return ownedByDynamicImport(base); }); + }; + + if (ownedByDynamicImport(classInfo)) + { + return loadedOpaque(methodInfo->funcName); + } + auto symbolRefOp = builder.create( location, methodInfo->funcType, mlir::FlatSymbolRefAttr::get(builder.getContext(), methodInfo->funcName)); return builder.create(location, opaqueType, symbolRefOp); @@ -4355,7 +4387,14 @@ genContext); // the vtable, for a static read through the value (an abstract class has one for that) mlir::Value vtable; - if (classInfo->getHasVirtualTable()) + if (classInfo->isDynamicImport) + { + // the importer has no global of it: it is looked up in the library, as a vtable slot a + // library's class owns is (mlirGenClassVirtualTableDefinition) + auto vtableName = V(mlirGenStringValue(location, concat(classInfo->fullName, VTABLE_NAME), true)); + vtable = builder.create(location, opaqueType, vtableName); + } + else if (classInfo->getHasVirtualTable()) { // as an instance gets it (mlirGenSetVTableToInstance) auto vtableName = concat(classInfo->fullName, VTABLE_NAME); @@ -4380,7 +4419,11 @@ genContext); // the rtti: every class has one, and no two the same mlir::Value rtti; auto rttiName = concat(classInfo->fullName, RTTI_NAME); - if (auto rttiAddress = resolveFullNameIdentifier(location, rttiName, true, genContext)) + if (classInfo->isDynamicImport) + { + rtti = loadedOpaque(rttiName); + } + else if (auto rttiAddress = resolveFullNameIdentifier(location, rttiName, true, genContext)) { rtti = builder.create(location, opaqueType, rttiAddress); } @@ -4389,6 +4432,13 @@ genContext); rtti = builder.create(location, opaqueType, rttiName, ::mlir::IntegerAttr()); } + if (!newFunc || !constructorFunc || !rtti) + { + emitError(location) << "class '" << classInfo->fullName << "' of a shared library can't be used as a value: " + << "its functions can't be resolved"; + return mlir::failure(); + } + auto storageType = MLIRTypeHelper::getClassValueStorageType(builder.getContext()); auto storage = builder.create(location, storageType, mlir::ValueRange{vtable, newFunc, constructorFunc, rtti}); diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 2f1844040..301b293c6 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -9012,12 +9012,24 @@ class MLIRGenImpl assert(genContext.allowPartialResolve || fieldInfo.virtualIndex >= 0); + // a shared library's class: the importer keeps a pointer to the library's field + // (mlirGenClassStaticFieldMemberDynamicImport), but the library's vtable slot points at the + // field itself + auto fieldType = fieldInfo.type; + if (classInfo->isDynamicImport) + { + if (auto refType = dyn_cast(fieldType)) + { + fieldType = refType.getElementType(); + } + } + auto virtualSymbOp = builder.create( - location, mlir_ts::RefType::get(fieldInfo.type), vtableAccess, + location, mlir_ts::RefType::get(fieldType), vtableAccess, builder.getI32IntegerAttr(fieldInfo.virtualIndex), mlir::FlatSymbolRefAttr::get(builder.getContext(), fieldInfo.globalVariableName)); - auto value = builder.create(location, fieldInfo.type, virtualSymbOp); + auto value = builder.create(location, fieldType, virtualSymbOp); return value; #endif } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 940be457c..f285b5095 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1639,6 +1639,7 @@ tslang_add_test(NAME test-compile-export-import-class-indexer COMMAND test-runne tslang_add_test(NAME test-compile-export-import-interface-indexer COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/import_interface_indexer.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_interface_indexer.ts") tslang_add_test(NAME test-compile-export-import-class-implements-interface-multilevel COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_implements_interface_multilevel.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_implements_interface_multilevel.ts") tslang_add_test(NAME test-compile-export-import-interface-generic-method COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/import_interface_generic_method.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_interface_generic_method.ts") +tslang_add_test(NAME test-compile-export-import-class-values COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_values.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_values.ts") tslang_add_test(NAME test-compile-export-import-class-implements-interface-optional COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_implements_interface_optional.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_implements_interface_optional.ts") tslang_add_test(NAME test-compile-export-import-class-implements-interface-abstract COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_implements_interface_abstract.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_implements_interface_abstract.ts") tslang_add_test(NAME test-compile-export-import-class-structural-interface COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_structural_interface.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_structural_interface.ts") @@ -1687,6 +1688,8 @@ set_tests_properties(test-compile-shared-import-unresolved-iface PROPERTIES PASS # Classes as values under every memory model (00class_values runs under gc above) foreach(class_value_mm rc none own) tslang_add_test(NAME test-jit-00-class-values-${class_value_mm} COMMAND test-runner -jit -mm=${class_value_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_values.ts") + # ...and of a shared library's classes + tslang_add_test(NAME test-jit-shared-export-import-class-values-${class_value_mm} COMMAND test-runner -jit -shared -mm=${class_value_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_values.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_values.ts") endforeach() # ...a class whose constructor takes other arguments than its base's is no value of the base's type add_test(NAME test-compile-class-value-constructor-error @@ -1844,6 +1847,7 @@ tslang_add_test(NAME test-compile-shared-export-import-class-static COMMAND test # own. See class-implements-interface-dynamic-import-fix memory for the full account. tslang_add_test(NAME test-compile-shared-export-import-class-implements-interface-multilevel COMMAND test-runner -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_implements_interface_multilevel.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_implements_interface_multilevel.ts") tslang_add_test(NAME test-compile-shared-export-import-interface-generic-method COMMAND test-runner -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_interface_generic_method.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_interface_generic_method.ts") +tslang_add_test(NAME test-compile-shared-export-import-class-values COMMAND test-runner -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_values.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_values.ts") tslang_add_test(NAME test-compile-shared-export-import-class-implements-interface-optional COMMAND test-runner -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_implements_interface_optional.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_implements_interface_optional.ts") tslang_add_test(NAME test-compile-shared-export-import-class-structural-interface COMMAND test-runner -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_structural_interface.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_structural_interface.ts") # FIXED 2026-07-23 (was disabled): the "this.area()-returns-0-via-interface" symptom had nothing @@ -1942,6 +1946,7 @@ tslang_add_test(NAME test-jit-shared-export-import-class-abstract COMMAND test-r tslang_add_test(NAME test-jit-shared-export-import-class-static COMMAND test-runner -jit -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_static.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_static.ts") tslang_add_test(NAME test-jit-shared-export-import-class-implements-interface-multilevel COMMAND test-runner -jit -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_implements_interface_multilevel.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_implements_interface_multilevel.ts") tslang_add_test(NAME test-jit-shared-export-import-interface-generic-method COMMAND test-runner -jit -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_interface_generic_method.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_interface_generic_method.ts") +tslang_add_test(NAME test-jit-shared-export-import-class-values COMMAND test-runner -jit -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_values.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_values.ts") tslang_add_test(NAME test-jit-shared-export-import-class-implements-interface-optional COMMAND test-runner -jit -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_implements_interface_optional.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_implements_interface_optional.ts") tslang_add_test(NAME test-jit-shared-export-import-class-structural-interface COMMAND test-runner -jit -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_structural_interface.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_structural_interface.ts") # FIXED 2026-07-23 (was disabled): see the matching test-compile-shared-export-import-class-implements-interface-abstract comment above (DeclarationPrinter dropped `abstract`, shifting the reimported vtable's slots). diff --git a/tslang/test/tester/tests/export_class_values.ts b/tslang/test/tester/tests/export_class_values.ts new file mode 100644 index 000000000..e453ae823 --- /dev/null +++ b/tslang/test/tester/tests/export_class_values.ts @@ -0,0 +1,44 @@ +// classes another module takes as values (import_class_values.ts) +export namespace K { + export class Shape { + static count = 1; + + constructor(public s: number) {} + + static label() { + return "shape"; + } + + area() { + return 0; + } + } + + export class Square extends Shape { + static count = 2; + + static label() { + return "square"; + } + + area() { + return this.s * this.s; + } + } + + export abstract class Kind { + static id() { + return 1; + } + } + + export class Concrete extends Kind { + static id() { + return 2; + } + } + + export function make(c: typeof Shape, s: number) { + return new c(s); + } +} diff --git a/tslang/test/tester/tests/import_class_values.ts b/tslang/test/tester/tests/import_class_values.ts new file mode 100644 index 000000000..336a9ff5b --- /dev/null +++ b/tslang/test/tester/tests/import_class_values.ts @@ -0,0 +1,35 @@ +import './export_class_values' + +// a class of this module, extending one of the other +class Triple extends K.Shape { + area() { + return 3 * this.s * this.s; + } +} + +function areaOf(c: typeof K.Shape, s: number) { + return new c(s).area(); +} + +function main() { + assert(areaOf(K.Square, 3) == 9 && areaOf(K.Shape, 3) == 0 && areaOf(Triple, 1) == 3, "new through the value"); + + const kinds: (typeof K.Shape)[] = [K.Square, Triple, K.Shape]; + let total: number = 0; + for (const k of kinds) { + total += k.count; + } + + assert(total == 2 + 1 + 1, "static field through the value"); + + const c: typeof K.Shape = K.Square; + assert(c.label() == "square" && c == K.Square && c != K.Shape, "static method, equality"); + + assert(K.make(K.Square, 4).area() == 16 && K.make(Triple, 2).area() == 12, "given to the other module"); + + const k: typeof K.Kind = K.Kind; + const n: typeof K.Kind = K.Concrete; + assert(k.id() == 1 && n.id() == 2, "abstract class"); + + print("done."); +}