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
40 changes: 39 additions & 1 deletion tslang/docs/generic-interface-methods-design.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Generic methods in interfaces (and virtual generic class methods): design

Status: **proposed, not implemented**. Written 2026-10-29, to be picked up later.
Status: **option A implemented for interfaces, D for classes** (2026-10-29); see §7. Virtual dispatch of
generic class methods through a base class is not done.

## 1. What fails today

Expand Down Expand Up @@ -76,3 +77,40 @@ A vtable slot holds one function pointer. A generic method has no single functio

- Generic *interfaces* (`interface Box<T>`) already work: they are instantiated per type argument. This document is only about generic *methods*.
- Making generic class methods virtual where nothing overrides them: a direct instantiation stays faster.

## 7. What is implemented

**Interfaces (option A).**
- **The slot** (`getInterfaceMethodNameAndType`): a generic method's signature is generated with each type
parameter bound to `any`, and `InterfaceMethodInfo::genericSignature` keeps the AST for call sites.
A type parameter must be the whole type of a parameter or of the result: `T[]`, `[A, B]`, `A | B` or
`Box<T>` erased are not laid out as their instantiations are, so they are an error at the declaration.
- **The implementer** (`findErasedGenericMethod`, `instantiateErasedGenericFunction`): when a class's
vtable for the interface finds no plain method of the name, the class's generic method (or its
nearest base's) is instantiated with `any` and fills the slot. Kept in `ClassInfo::erasedGenericMethods`,
and made again when the symbol is not in the current module (the discovery pass drops its module).
An object literal with an untyped arrow (`{ map: (x) => x }`) fills the slot as for any method.
- **The call** (`mlirGenCallExpression`, `instantiateErasedGenericResultType`): an interface symbol ref of a
generic method is remembered (`erasedGenericCallees`); its call infers the type arguments from the
arguments when none are given (the signature with each type parameter as a named generic type, matched
by `inferType`), makes the call through the slot, and casts the `any` result to the instantiated
result type - the checked `<T>anyValue` cast.
- **Cross-module**: an exported interface with a generic method is exported as its source
(`addInterfaceSourceToExport`), as a generic interface is, so the importer has the generic signature
and not only the erased slot.

**Classes (option D).** A generic method declared in a class whose base has a generic method of that name
is an error: a call through the base class would not reach it.

**Limits.**
- A body that depends on its type parameter's real type (`sizeof<T>()`) runs with `any` through an
interface; it is not rejected.
- Under own, a class object unboxed from the `any` result is a borrow of the box: it can be read, not
given on as another `any` argument. An object literal and a class implementing the same interface
method that returns its parameter disagree on the family's result under own, as a non-generic
`map(x: any): any` does.

**Tests.** `00interface_generic_method` (explicit and inferred type arguments, a string, a class object,
two implementers, an inherited generic method, a direct call), `own_interface_generic_method` (under own,
rc, gc and none, with churn), `export_interface_generic_method` / `import_interface_generic_method` (an
exported interface, class and function used from another module, plain and `-shared`).
9 changes: 9 additions & 0 deletions tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
#include "TypeScript/MLIRLogic/MLIRHelper.h"

#include "llvm/ADT/StringMap.h"

#include <deque>
#include "llvm/Support/Debug.h"

#define DEBUG_TYPE "mlir"
Expand Down Expand Up @@ -238,6 +240,9 @@ struct InterfaceMethodInfo
bool isConditional;
int interfacePosIndex;
int virtualIndex;
// a generic method (`map<T>(x: T): T`): its slot takes and returns `any` for each type parameter
// (funcType), and a call instantiates this signature for its type arguments to unbox the result
SignatureDeclarationBase genericSignature;
};

struct InterfaceAccessorInfo
Expand Down Expand Up @@ -783,6 +788,10 @@ struct ClassInfo

llvm::SmallVector<GenericMethodInfo> staticGenericMethods;

// its generic methods instantiated with `any` for each type parameter, filling the slots of the
// interfaces it implements (a deque: a vtable's callback hands out references to them)
std::deque<MethodInfo> erasedGenericMethods;

llvm::SmallVector<AccessorInfo> accessors;

llvm::SmallVector<IndexInfo> indexes;
Expand Down
96 changes: 96 additions & 0 deletions tslang/lib/TypeScript/MLIRGenAccessCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1743,10 +1743,106 @@ namespace mlirgen
return generate();
}

mlir::Type MLIRGenImpl::instantiateErasedGenericResultType(mlir::Location location, SignatureDeclarationBase signature,
mlir::Type thisType, NodeArray<TypeNode> typeArguments,
SmallVector<mlir::Value, 4> &operands,
const GenContext &genContext)
{
llvm::SmallVector<TypeParameterDOM::TypePtr> typeParams;
if (mlir::failed(processTypeParameters(signature->typeParameters, typeParams, genContext)))
{
return mlir::Type();
}

GenContext signatureGenContext(genContext);
signatureGenContext.clearScopeVars();
signatureGenContext.thisType = thisType;
signatureGenContext.typeParamsWithArgs.clear();
if (typeArguments.size() > 0)
{
auto [result, isGeneric] = zipTypeParametersWithArguments(location, typeParams, typeArguments,
signatureGenContext.typeParamsWithArgs, genContext);
if (mlir::failed(result) || isGeneric == IsGeneric::True)
{
return mlir::Type();
}
}
else
{
// each type parameter from the arguments, matched with the parameters it types
GenContext templateGenContext(signatureGenContext);
for (auto &typeParam : typeParams)
{
templateGenContext.typeParamsWithArgs[typeParam->getName()] =
std::make_pair(typeParam, getNamedGenericType(typeParam->getName()));
}

auto [proto, templateType, results] = mlirGenFunctionSignaturePrototype(signature, true, templateGenContext);
if (!templateType || templateType.getNumInputs() < operands.size())
{
return mlir::Type();
}

StringMap<mlir::Type> inferred;
auto offset = templateType.getNumInputs() - operands.size();
for (auto [index, operand] : llvm::enumerate(operands))
{
inferType(location, templateType.getInput(offset + index), operand.getType(), inferred, genContext);
}

for (auto &typeParam : typeParams)
{
auto found = inferred.find(typeParam->getName());
if (found == inferred.end() || !found->getValue() || mth.isGenericType(found->getValue()))
{
return mlir::Type();
}

signatureGenContext.typeParamsWithArgs[typeParam->getName()] =
std::make_pair(typeParam, mth.wideStorageType(found->getValue()));
}
}

auto [proto, funcType, results] = mlirGenFunctionSignaturePrototype(signature, true, signatureGenContext);
if (!funcType || funcType.getNumResults() != 1 || mth.isGenericType(funcType.getResult(0)))
{
return mlir::Type();
}

return funcType.getResult(0);
}

ValueOrLogicalResult MLIRGenImpl::mlirGenCallExpression(mlir::Location location, mlir::Value funcResult,
NodeArray<TypeNode> typeArguments, SmallVector<mlir::Value, 4> &operands,
const GenContext &genContext)
{
// a generic interface method, erased to `any`: called as it is, and its result unboxed to the
// type its type arguments give it - the checked cast `<T>anyValue` is
if (auto *calleeOp = funcResult ? funcResult.getDefiningOp() : nullptr)
{
auto erased = erasedGenericCallees.find(calleeOp);
if (erased != erasedGenericCallees.end())
{
auto signature = erased->second;
erasedGenericCallees.erase(erased);

auto thisType = calleeOp->getOperand(0).getType();
auto resultType =
instantiateErasedGenericResultType(location, signature, thisType, typeArguments, operands, genContext);
auto callResult = mlirGenCallExpression(location, funcResult, {}, operands, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(callResult)
auto callValue = V(callResult);
if (!resultType || resultType == callValue.getType() || mth.isNoneType(resultType) ||
resultType == getVoidType())
{
return callValue;
}

CAST_A(unboxed, location, resultType, callValue, genContext);
return unboxed;
}
}

GenContext specGenContext(genContext);
specGenContext.callOperands = operands;

Expand Down
94 changes: 94 additions & 0 deletions tslang/lib/TypeScript/MLIRGenClasses.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2804,6 +2804,71 @@ genContext);
return mlir::failure();
}

std::pair<mlir::LogicalResult, MethodInfo *> MLIRGenImpl::findErasedGenericMethod(mlir::Location location,
ClassInfo::TypePtr classInfo,
mlir::StringRef name,
const GenContext &genContext)
{
// made before, and in this module: a discovery pass makes its own in a module it then drops
for (auto &erased : classInfo->erasedGenericMethods)
{
if (erased.name == name && theModule.lookupSymbol(erased.funcName))
{
return {mlir::success(), &erased};
}
}

auto index = classInfo->getGenericMethodIndex(name);
if (index < 0)
{
// the nearest base class's
for (auto &base : classInfo->baseClasses)
{
auto [result, found] = findErasedGenericMethod(location, base, name, genContext);
if (mlir::failed(result) || found)
{
return {result, found};
}
}

return {mlir::success(), nullptr};
}

auto &genericMethodInfo = classInfo->staticGenericMethods[index];
if (genericMethodInfo.isStatic)
{
return {mlir::success(), nullptr};
}

auto [result, funcType, funcName] =
instantiateErasedGenericFunction(location, genericMethodInfo.funcProto->getName(), genContext);
if (mlir::failed(result))
{
emitError(location) << "can't instantiate generic method '" << name << "' of class '" << classInfo->fullName
<< "' with 'any' for an interface";
return {mlir::failure(), nullptr};
}

for (auto &erased : classInfo->erasedGenericMethods)
{
if (erased.name == name)
{
erased.funcName = funcName;
erased.funcType = funcType;
return {mlir::success(), &erased};
}
}

MethodInfo methodInfo{};
methodInfo.name = name.str();
methodInfo.funcName = funcName;
methodInfo.funcType = funcType;
methodInfo.virtualIndex = -1;
methodInfo.accessLevel = genericMethodInfo.accessLevel;
classInfo->erasedGenericMethods.push_back(methodInfo);
return {mlir::success(), &classInfo->erasedGenericMethods.back()};
}

mlir::LogicalResult MLIRGenImpl::mlirGenClassVirtualTableDefinitionForInterface(mlir::Location location,
ClassInfo::TypePtr newClassPtr,
InterfaceInfo::TypePtr newInterfacePtr,
Expand Down Expand Up @@ -3016,6 +3081,18 @@ genContext);
},
[&](std::string name, mlir_ts::FunctionType funcType, bool isConditional, int interfacePosIndex) -> std::pair<MethodInfo &, mlir::LogicalResult> {
auto foundMethodPtr = newClassPtr->findMethod(name);
// a generic method fills the interface's slot for it erased to `any`
if (!foundMethodPtr)
{
auto [result, erasedMethodPtr] = findErasedGenericMethod(location, newClassPtr, name, genContext);
if (mlir::failed(result))
{
return {emptyMethod, mlir::failure()};
}

foundMethodPtr = erasedMethodPtr;
}

if (!foundMethodPtr)
{
// TODO: generate method wrapper for calling new/ctor method
Expand Down Expand Up @@ -4027,6 +4104,23 @@ genContext);
{
if (classMethodMemberInfo.newClassPtr->getGenericMethodIndex(classMethodMemberInfo.methodName) < 0)
{
// a generic method is instantiated for the class a call names, never dispatched: an override
// would be skipped by every call through a base class's reference
std::function<bool(ClassInfo::TypePtr)> baseHasGeneric = [&](ClassInfo::TypePtr classInfo) {
return llvm::any_of(classInfo->baseClasses, [&](ClassInfo::TypePtr base) {
auto index = base->getGenericMethodIndex(classMethodMemberInfo.methodName);
return (index >= 0 && !base->staticGenericMethods[index].isStatic) || baseHasGeneric(base);
});
};
if (!classMethodMemberInfo.isStatic && baseHasGeneric(classMethodMemberInfo.newClassPtr))
{
emitError(loc(classMethodMemberInfo.classMember))
<< "generic method '" << classMethodMemberInfo.methodName
<< "' overrides a base class's generic method, which a call through the base class would not "
"reach: generic methods are not virtual (declare it in an interface to dispatch it)";
return mlir::failure();
}

llvm::SmallVector<TypeParameterDOM::TypePtr> typeParameters;
if (mlir::failed(
processTypeParameters(funcLikeDeclaration->typeParameters, typeParameters, genContext)))
Expand Down
54 changes: 54 additions & 0 deletions tslang/lib/TypeScript/MLIRGenGenerics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -995,6 +995,60 @@ namespace mlirgen
return mlir::success();
}

std::tuple<mlir::LogicalResult, mlir_ts::FunctionType, std::string> MLIRGenImpl::instantiateErasedGenericFunction(
mlir::Location location, StringRef name, const GenContext &genContext)
{
auto functionGenericTypeInfo = getGenericFunctionInfoByFullName(name);
if (!functionGenericTypeInfo)
{
emitError(location) << "can't find information about generic function. " << name;
return {mlir::failure(), mlir_ts::FunctionType(), ""};
}

MLIRNamespaceGuard ng(currentNamespace);
currentNamespace = functionGenericTypeInfo->elementNamespace;

SourceFileScope sourceFileScope(*this, functionGenericTypeInfo->sourceFile, functionGenericTypeInfo->fileName);

GenContext genericTypeGenContext(genContext);
genericTypeGenContext.specialization = true;
genericTypeGenContext.instantiateSpecializedFunction = true;
genericTypeGenContext.typeParamsWithArgs = functionGenericTypeInfo->typeParamsWithArgs;
genericTypeGenContext.thisType = functionGenericTypeInfo->thisType;
genericTypeGenContext.thisClassType = functionGenericTypeInfo->thisClassType;
for (auto &typeParam : functionGenericTypeInfo->typeParams)
{
genericTypeGenContext.typeParamsWithArgs[typeParam->getName()] = std::make_pair(typeParam, getAnyType());
}

if (functionGenericTypeInfo->processing)
{
auto [fullName, funcName] = getNameOfFunction(functionGenericTypeInfo->functionDeclaration, genericTypeGenContext);
if (auto funcType = lookupFunctionTypeMap(fullName))
{
return {mlir::success(), funcType, fullName};
}

emitError(location) << "can't instantiate '" << name << "' with 'any' while it is being instantiated";
return {mlir::failure(), mlir_ts::FunctionType(), ""};
}

mlir::OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointToStart(theModule.getBody());

functionGenericTypeInfo->processing = true;
auto [result, funcOp, funcName, isGeneric] =
mlirGenFunctionLikeDeclaration(functionGenericTypeInfo->functionDeclaration, genericTypeGenContext);
functionGenericTypeInfo->processing = false;
if (mlir::failed(result) || !funcOp)
{
return {mlir::failure(), mlir_ts::FunctionType(), ""};
}

functionGenericTypeInfo->processed = true;
return {mlir::success(), funcOp.getFunctionType(), funcName};
}

std::tuple<mlir::LogicalResult, mlir_ts::FunctionType, std::string> MLIRGenImpl::instantiateSpecializedFunction(
mlir::Location location, StringRef name, NodeArray<TypeNode> typeArguments, bool skipThisParam,
SmallVector<mlir::Value, 4> &operands, const GenContext &genContext)
Expand Down
Loading
Loading