From 84ab8120ddd7eb8e80a126d5cf35a6f6e930257b Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 6 Nov 2026 17:53:45 +0000 Subject: [PATCH] Mixins as the handbook writes them: a generic function given a class extends it `function Scale(Base: TBase) { return class extends Base {...} }` called as `Scale(Sprite)` specializes Scale for the class Sprite, so the class it returns extends Sprite at compile time. Four things stood in the way: - The heritage clause wanted only the base's type, but a base named by a parameter was read by a load emitted at module level ("null operand found"). The load is erased. - A class name given to a parameter declared as a bare type parameter has no run-time value of the class type T is inferred as; the call passes a null of that type, which the specialization never reads. A parameter typed otherwise (`f(a: A)` called as `f(A)`) is left as it was. - Against a construct signature, a class without a constructor of its own is made by `new A()`, and a method without a return type matches a void one. - A class extending a `typeof A` value (known at run time only) gets an error naming the generic form instead of "class cannot extend type". T stays the class itself, not `typeof A`: a `typeof A` value may hold a subclass laid out otherwise. Tests 00mixins (gc, rc, none, own) and mixin_runtime_base_error; the design is in docs/classes-as-values-design.md section 6. Co-Authored-By: Claude Opus 5.5 --- tslang/docs/classes-as-values-design.md | 45 +++++- .../TypeScript/MLIRLogic/MLIRTypeHelper.h | 21 ++- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 70 ++++++++++ tslang/lib/TypeScript/MLIRGenClasses.cpp | 22 ++- tslang/lib/TypeScript/MLIRGenImpl.h | 2 + tslang/test/tester/CMakeLists.txt | 10 ++ tslang/test/tester/tests/00mixins.ts | 129 ++++++++++++++++++ .../tester/tests/mixin_runtime_base_error.ts | 16 +++ tslang/test/tester/verify-ownership.cmake | 4 +- 9 files changed, 308 insertions(+), 11 deletions(-) create mode 100644 tslang/test/tester/tests/00mixins.ts create mode 100644 tslang/test/tester/tests/mixin_runtime_base_error.ts diff --git a/tslang/docs/classes-as-values-design.md b/tslang/docs/classes-as-values-design.md index ea1f2f166..0ceea9e93 100644 --- a/tslang/docs/classes-as-values-design.md +++ b/tslang/docs/classes-as-values-design.md @@ -94,7 +94,7 @@ A local class used as a value (`return Counter`) carries its captures. Its value ## 4. Non-goals -- `abstract new () => A` construct signatures and mixins (`function Mixin {}>(Base: T)`): these build on class values but need generic construct signatures. A follow-up. +- `abstract new () => A` construct signatures, and values of a construct-signature type (`const B: new () => {} = A; new B()`). Mixins as the handbook writes them work without them (ยง6). - `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 @@ -113,7 +113,9 @@ between the value and that tuple, or to the value of a base class, lowers to not **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. + variable or field, an array element, a return. A local `const C = A` stays a compile-time alias; a + module-level `const C = A` or a `let C = A` is not supported yet (the class name has no run-time value of + the instance type it is given). - **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 @@ -161,3 +163,42 @@ initializers (`generatedStatements`) with its body, so what they read is found a C++ slots (one by hand, as C++ would), in an array, compared; under gc, rc, none and own. - **`class_value_constructor_error`**, **`class_local_capture_error`**, **`class_field_capture_error`** and **`cpp_class_value_error`:** the errors. + +## 6. Mixins + +```ts +type Constructor = new (...args: any[]) => {}; +function Scale(Base: TBase) { + return class Scaling extends Base { _scale: number = 1; }; +} +const EightBitSprite = Scale(Sprite); +``` + +**A specialization per class.** `Scale(Sprite)` infers `TBase` as the class `Sprite` (its `ClassType`, not +`typeof Sprite`) and specializes `Scale` for it, so `Scaling` extends `Sprite` at compile time, with an +ordinary layout and vtable. Chains (`Loud(Tagged(Sprite))`) specialize the outer mixin for the inner one's +class. + +What makes it work: +- **The base's type only:** the heritage clause wants the base's type. A base named by a parameter was read by + a load emitted at module level, outside the function owning the parameter ("null operand found"); the load + is erased (`mlirGenClassHeritageClause`). +- **The argument:** a class name given to a parameter declared as a bare type parameter has no run-time value + of the instance type T is inferred as. The specialization uses the class at compile time only (`extends Base`, + `new Base()`), so the call passes a null of that type (`classNamesGivenToTypeParameters`). A parameter typed + otherwise (`f(a: A)` called as `f(A)`) is left as it was: an error. +- **The constraint** (`extendsType` against a construct signature): a class without a constructor of its own + is made by `new A()`; a method without a return type matches a `void` one (`{ setPos(x, y): void }`). + +**Not supported:** +- **A base known at run time:** `function make(B: typeof A) { return class extends B {} }`. `typeof A` may hold + a subclass of A, laid out otherwise, so it's an error that names the generic form. For the same reason + `TBase` is not inferred as `typeof A`, and `Scale(Sprite)` does not satisfy the constraint. +- **`applyMixins`** (copying prototype members at run time): there are no prototypes. A merged + `interface Sprite extends Jumpable, Duckable {}` adds nothing to the class. +- **An integer-initialized field** (`x = 0`) is `s32`, which does not satisfy a `{ x: number }` constraint; + write `x: number = 0`. + +Tests: **`00mixins`** (the handbook's constructor and constrained mixins, chains, a mixin over a class +without a constructor, super calls, a class declared in a generic function) under gc, rc, none and own; +**`mixin_runtime_base_error`**. diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h index 5a0e59336..fd4c98e4c 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h @@ -3065,7 +3065,14 @@ class MLIRTypeHelper } } - // compare return types + // compare return types; a function with no result is a void one (`setPos(x) { ... }` is a + // `setPos(x): void`) + auto isNoResult = [&](mlir::Type type) { return !type || isNoneType(type) || isa(type); }; + if (isNoResult(srcReturnType) && isNoResult(extReturnType)) + { + return ExtendsResult::True; + } + return extendsType(location, srcReturnType, extReturnType, typeParamsWithArgs); } @@ -3387,14 +3394,16 @@ class MLIRTypeHelper { if (auto srcClassInfo = getClassInfoByFullName(srcClassType.getName().getValue())) { - // we have class - if (!srcClassInfo->getHasConstructor()) + // find constructor type + auto constrMethod = srcClassInfo->findMethod(CONSTRUCTOR_NAME); + if (!constrMethod) { - return ExtendsResult::False; + // a class without a constructor of its own is made by `new A()` + auto defaultConstrType = mlir_ts::FunctionType::get( + srcClassType.getContext(), {srcClassInfo->classType}, {srcClassInfo->classType}, false); + return extendsTypeFuncTypes(location, defaultConstrType, extendType, typeParamsWithArgs, 1/*because of this param*/); } - // find constructor type - auto constrMethod = srcClassInfo->findMethod(CONSTRUCTOR_NAME); auto constrWithRetType = mlir_ts::FunctionType::get( constrMethod->funcType.getContext(), constrMethod->funcType.getInputs(), diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 7bd569881..bad5d4d71 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -1847,6 +1847,63 @@ namespace mlirgen return funcType.getResult(0); } + // A class named as the argument of a generic function's parameter declared as a bare type parameter + // (`function Mixin(Base: T)` called as `Mixin(A)`): T is inferred as the class, and the + // specialization uses it at compile time only. Any other parameter typed by a class keeps the class name + // as it is (no run-time value: an error). + SmallVector MLIRGenImpl::classNamesGivenToTypeParameters(mlir::Value funcResult, + ArrayRef operands) + { + SmallVector indexes; + auto symbolOp = funcResult ? funcResult.getDefiningOp() : mlir_ts::SymbolRefOp(); + if (!symbolOp || !symbolOp->hasAttrOfType(GENERIC_ATTR_NAME) + || llvm::none_of(operands, [](mlir::Value operand) { return operand && operand.getDefiningOp(); })) + { + return indexes; + } + + auto functionGenericTypeInfo = getGenericFunctionInfoByFullName(symbolOp.getIdentifierAttr().getValue()); + if (!functionGenericTypeInfo || !functionGenericTypeInfo->functionDeclaration) + { + return indexes; + } + + auto declarationParams = functionGenericTypeInfo->functionDeclaration->parameters; + for (auto [index, operand] : enumerate(operands)) + { + if (index >= declarationParams.size() || declarationParams[index]->dotDotDotToken) + { + break; + } + + if (!operand || !operand.getDefiningOp()) + { + continue; + } + + auto paramTypeNode = declarationParams[index]->type; + if (!paramTypeNode || paramTypeNode != SyntaxKind::TypeReference) + { + continue; + } + + auto typeReference = paramTypeNode.as(); + if (typeReference->typeArguments.size() > 0) + { + continue; + } + + auto typeName = MLIRHelper::getName(typeReference->typeName); + if (llvm::any_of(functionGenericTypeInfo->typeParams, + [&](auto &typeParam) { return typeParam->getName() == typeName; })) + { + indexes.push_back(index); + } + } + + return indexes; + } + ValueOrLogicalResult MLIRGenImpl::mlirGenCallExpression(mlir::Location location, mlir::Value funcResult, NodeArray typeArguments, SmallVector &operands, const GenContext &genContext) @@ -1881,11 +1938,24 @@ namespace mlirgen GenContext specGenContext(genContext); specGenContext.callOperands = operands; + auto classNameOperands = classNamesGivenToTypeParameters(funcResult, operands); + // get function ref. auto result = mlirGenSpecialized(location, funcResult, typeArguments, operands, specGenContext); EXIT_IF_FAILED(result) auto actualFuncRefValue = V(result); + // the specialization knows the class by its type (`T` is the class: `class extends Base`, `new Base()` + // name it at compile time), so the argument itself is never read: a class name has no run-time value + // of the instance type it was inferred as. Give the parameter a null of that type + for (auto index : classNameOperands) + { + auto classType = operands[index].getType(); + // a cast of its own: the checked one (strict null) refuses null for a class type + mlir::Value nullValue = builder.create(location, getNullType()); + operands[index] = builder.create(location, classType, nullValue); + } + if (!result.value && genContext.allowPartialResolve) { return mlir::success(); diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index f1d128d37..9855ad55e 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -1328,9 +1328,19 @@ namespace mlirgen { auto result = mlirGen(extendingType, genContext); EXIT_IF_FAILED_OR_NO_VALUE(result) - auto baseType = V(result); + auto baseValue = V(result); + auto baseType = baseValue.getType(); + + // only the base's type is wanted. A base named by a parameter (`class extends Base` in a + // mixin) is read by a load emitted here, outside the function that owns the parameter + if (auto baseOp = baseValue.getDefiningOp(); + baseOp && !isa(baseOp) && baseOp->use_empty()) + { + baseOp->erase(); + } + auto success = false; - mlir::TypeSwitch(baseType.getType()) + mlir::TypeSwitch(baseType) .template Case([&](auto baseClassType) { auto baseName = baseClassType.getName().getValue(); auto fieldId = MLIRHelper::TupleFieldName(baseName, builder.getContext()); @@ -1369,6 +1379,14 @@ namespace mlirgen success = true; }) + .template Case([&](auto classValueType) { + // `typeof A` may hold a subclass of A, laid out otherwise: the base is known at run + // time only. A generic mixin given the class (`Mixin(A)`) knows it at compile time + emitError(loc(extendingType)) + << "class cannot extend a class value (" << to_print(classValueType) + << "): its class is known at run time only. Take the base as a type parameter, " + "` {}>(Base: T)`, and give it the class"; + }) .Default([&](auto type) { // e.g. `class Sub extends SomeInterface {}` - real TypeScript rejects // extending an interface (only a class/constructor value is allowed diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index ce5b99239..24cb78a01 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -10068,6 +10068,8 @@ class MLIRGenImpl std::optional mlirGenArrayInsertWithSpread( mlir::Location location, mlir::Value funcResult, NodeArray arguments, const GenContext &genContext); + SmallVector classNamesGivenToTypeParameters(mlir::Value funcResult, ArrayRef operands); + ValueOrLogicalResult mlirGenCallExpression(mlir::Location location, mlir::Value funcResult, NodeArray typeArguments, SmallVector &operands, const GenContext &genContext); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index ce6360ce3..351379912 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -753,6 +753,7 @@ tslang_add_test(NAME test-compile-00-function-fewer-parameters COMMAND test-runn 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-mixins COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00mixins.ts") tslang_add_test(NAME test-compile-00-class-arrow-fields COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_arrow_fields.ts") tslang_add_test(NAME test-compile-00-class-arrow-getter COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_arrow_getter.ts") tslang_add_test(NAME test-compile-00-interface-generic-method COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_generic_method.ts") @@ -1769,6 +1770,15 @@ 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") +# Mixins (a generic function given a class) under every memory model +foreach(mixin_mm gc rc none own) + tslang_add_test(NAME test-jit-00-mixins-${mixin_mm} COMMAND test-runner -jit -mm=${mixin_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00mixins.ts") +endforeach() +# ...a class extending a class value known at run time only is an error +add_test(NAME test-compile-mixin-runtime-base-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/mixin_runtime_base_error.ts") +set_tests_properties(test-compile-mixin-runtime-base-error PROPERTIES PASS_REGULAR_EXPRESSION "class cannot extend a class value \\(typeof A\\): its class is known at run time only" + 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") diff --git a/tslang/test/tester/tests/00mixins.ts b/tslang/test/tester/tests/00mixins.ts new file mode 100644 index 000000000..963a0312a --- /dev/null +++ b/tslang/test/tester/tests/00mixins.ts @@ -0,0 +1,129 @@ +// Mixins as the TypeScript handbook writes them: a generic function taking a class (`Base: TBase`, TBase +// constrained by a construct signature) and returning a class that extends it. Each call with a class is a +// specialization of its own, so the returned class extends that class at compile time. +type Constructor = new (...args: any[]) => {}; +type GConstructor = new (...args: any[]) => T; + +class Sprite { + name: string = ""; + x: number = 0; + y: number = 0; + + constructor(name: string) { + this.name = name; + } + + setPos(x: number, y: number) { + this.x = x; + this.y = y; + } + + describe(): string { + return "sprite " + this.name; + } +} + +// no constructor of its own +class Point { + x: number = 1; +} + +// a constructor mixin +function Scale(Base: TBase) { + return class Scaling extends Base { + _scale: number = 1; + + setScale(scale: number) { + this._scale = scale; + } + + get scale(): number { + return this._scale; + } + }; +} + +function Tagged(Base: TBase) { + return class extends Base { + tag: string = "tagged"; + }; +} + +// constrained mixins: what the base must have, as a field or a method (one without a return type is a void one) +type Positionable = GConstructor<{ setPos: (x: number, y: number) => void }>; +type Describable = GConstructor<{ describe(): string }>; +type HasX = GConstructor<{ x: number }>; + +function Jumpable(Base: TBase) { + return class Jumpable extends Base { + jump() { + this.setPos(0, 20); + } + }; +} + +function Loud(Base: TBase) { + return class extends Base { + describe(): string { + return super.describe() + "!"; + } + }; +} + +function Doubled(Base: TBase) { + return class extends Base { + double() { + return this.x * 2; + } + }; +} + +// a class declared in the mixin's body, not returned +function makeTagged(Base: TBase) { + class Local extends Base { + local = 4; + } + + return new Local(); +} + +const EightBitSprite = Scale(Sprite); +const JumpSprite = Jumpable(Sprite); +const LoudSprite = Loud(Sprite); +const TaggedPoint = Tagged(Point); +const DoubledPoint = Doubled(Point); +// mixins applied to a mixin's class +const LoudTaggedSprite = Loud(Tagged(Sprite)); +const ScaledJumpSprite = Scale(Jumpable(Sprite)); + +function main() { + const flappy = new EightBitSprite("Bird"); + flappy.setScale(0.8); + assert(flappy.name == "Bird" && flappy.scale == 0.8, "constructor mixin"); + assert(flappy instanceof Sprite, "a mixin's class extends its base"); + + const jumper = new JumpSprite("J"); + jumper.jump(); + assert(jumper.y == 20, "constrained mixin calls the base's method"); + + const loud = new LoudSprite("L"); + assert(loud.describe() == "sprite L!", "mixin overrides through super"); + const asSprite: Sprite = loud; + assert(asSprite.describe() == "sprite L!", "override seen through the base"); + + const point = new TaggedPoint(); + assert(point.x == 1 && point.tag == "tagged", "base without a constructor"); + assert(new DoubledPoint().double() == 2, "field constraint"); + + const loudTagged = new LoudTaggedSprite("T"); + assert(loudTagged.tag == "tagged" && loudTagged.describe() == "sprite T!", "chained mixins"); + + const scaledJumper = new ScaledJumpSprite("S"); + scaledJumper.jump(); + scaledJumper.setScale(2); + assert(scaledJumper.y == 20 && scaledJumper.scale == 2, "chained constrained mixin"); + + assert(makeTagged(Point).local == 4 && makeTagged(Point).x == 1, "class declared in a generic function"); + + print("done."); +} diff --git a/tslang/test/tester/tests/mixin_runtime_base_error.ts b/tslang/test/tester/tests/mixin_runtime_base_error.ts new file mode 100644 index 000000000..27f809c60 --- /dev/null +++ b/tslang/test/tester/tests/mixin_runtime_base_error.ts @@ -0,0 +1,16 @@ +// A class extending a class value known only at run time: `typeof A` may hold a subclass of A, whose layout +// is not A's, so its class can't be laid out here. A generic mixin given the class itself (`Mixin(A)`) is. +class A { + a = 1; +} + +function make(B: typeof A) { + return class extends B { + b = 2; + }; +} + +function main() { + const C = make(A); + print(new C().b); +} diff --git a/tslang/test/tester/verify-ownership.cmake b/tslang/test/tester/verify-ownership.cmake index da143b8c4..884a08bdb 100644 --- a/tslang/test/tester/verify-ownership.cmake +++ b/tslang/test/tester/verify-ownership.cmake @@ -53,7 +53,9 @@ set(not_compilable_alone class_value_constructor_error.ts class_local_capture_error.ts class_field_capture_error.ts - cpp_class_value_error.ts) + cpp_class_value_error.ts + # an error by design (test-compile-mixin-runtime-base-error) + mixin_runtime_base_error.ts) file(GLOB corpus "${TESTS_DIR}/*.ts") list(SORT corpus)