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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 43 additions & 2 deletions tslang/docs/classes-as-values-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends new (...a: any[]) => {}>(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
Expand All @@ -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
Expand Down Expand Up @@ -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<TBase extends Constructor>(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<typeof Sprite>(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`**.
21 changes: 15 additions & 6 deletions tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::VoidType>(type); };
if (isNoResult(srcReturnType) && isNoResult(extReturnType))
{
return ExtendsResult::True;
}

return extendsType(location, srcReturnType, extReturnType, typeParamsWithArgs);

}
Expand Down Expand Up @@ -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(),
Expand Down
70 changes: 70 additions & 0 deletions tslang/lib/TypeScript/MLIRGenAccessCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends Ctor>(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<unsigned> MLIRGenImpl::classNamesGivenToTypeParameters(mlir::Value funcResult,
ArrayRef<mlir::Value> operands)
{
SmallVector<unsigned> indexes;
auto symbolOp = funcResult ? funcResult.getDefiningOp<mlir_ts::SymbolRefOp>() : mlir_ts::SymbolRefOp();
if (!symbolOp || !symbolOp->hasAttrOfType<mlir::BoolAttr>(GENERIC_ATTR_NAME)
|| llvm::none_of(operands, [](mlir::Value operand) { return operand && operand.getDefiningOp<mlir_ts::ClassRefOp>(); }))
{
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<mlir_ts::ClassRefOp>())
{
continue;
}

auto paramTypeNode = declarationParams[index]->type;
if (!paramTypeNode || paramTypeNode != SyntaxKind::TypeReference)
{
continue;
}

auto typeReference = paramTypeNode.as<TypeReferenceNode>();
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<TypeNode> typeArguments, SmallVector<mlir::Value, 4> &operands,
const GenContext &genContext)
Expand Down Expand Up @@ -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<mlir_ts::NullOp>(location, getNullType());
operands[index] = builder.create<mlir_ts::CastOp>(location, classType, nullValue);
}

if (!result.value && genContext.allowPartialResolve)
{
return mlir::success();
Expand Down
22 changes: 20 additions & 2 deletions tslang/lib/TypeScript/MLIRGenClasses.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::ClassRefOp>(baseOp) && baseOp->use_empty())
{
baseOp->erase();
}

auto success = false;
mlir::TypeSwitch<mlir::Type>(baseType.getType())
mlir::TypeSwitch<mlir::Type>(baseType)
.template Case<mlir_ts::ClassType>([&](auto baseClassType) {
auto baseName = baseClassType.getName().getValue();
auto fieldId = MLIRHelper::TupleFieldName(baseName, builder.getContext());
Expand Down Expand Up @@ -1369,6 +1379,14 @@ namespace mlirgen

success = true;
})
.template Case<mlir_ts::ClassValueType>([&](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, "
"`<T extends new (...args: any[]) => {}>(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
Expand Down
2 changes: 2 additions & 0 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -10068,6 +10068,8 @@ class MLIRGenImpl
std::optional<ValueOrLogicalResult> mlirGenArrayInsertWithSpread(
mlir::Location location, mlir::Value funcResult, NodeArray<Expression> arguments, const GenContext &genContext);

SmallVector<unsigned> classNamesGivenToTypeParameters(mlir::Value funcResult, ArrayRef<mlir::Value> operands);

ValueOrLogicalResult mlirGenCallExpression(mlir::Location location, mlir::Value funcResult,
NodeArray<TypeNode> typeArguments, SmallVector<mlir::Value, 4> &operands,
const GenContext &genContext);
Expand Down
10 changes: 10 additions & 0 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down
129 changes: 129 additions & 0 deletions tslang/test/tester/tests/00mixins.ts
Original file line number Diff line number Diff line change
@@ -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<T = {}> = 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<TBase extends Constructor>(Base: TBase) {
return class Scaling extends Base {
_scale: number = 1;

setScale(scale: number) {
this._scale = scale;
}

get scale(): number {
return this._scale;
}
};
}

function Tagged<TBase extends Constructor>(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<TBase extends Positionable>(Base: TBase) {
return class Jumpable extends Base {
jump() {
this.setPos(0, 20);
}
};
}

function Loud<TBase extends Describable>(Base: TBase) {
return class extends Base {
describe(): string {
return super.describe() + "!";
}
};
}

function Doubled<TBase extends HasX>(Base: TBase) {
return class extends Base {
double() {
return this.x * 2;
}
};
}

// a class declared in the mixin's body, not returned
function makeTagged<TBase extends Constructor>(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.");
}
Loading
Loading