diff --git a/tslang/docs/generic-interface-methods-design.md b/tslang/docs/generic-interface-methods-design.md index 403a9d422..7aaea4b3a 100644 --- a/tslang/docs/generic-interface-methods-design.md +++ b/tslang/docs/generic-interface-methods-design.md @@ -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 @@ -76,3 +77,40 @@ A vtable slot holds one function pointer. A generic method has no single functio - Generic *interfaces* (`interface Box`) 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` 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 `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()`) 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`). diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index 3a65c8a45..933cec3b0 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -6,6 +6,8 @@ #include "TypeScript/MLIRLogic/MLIRHelper.h" #include "llvm/ADT/StringMap.h" + +#include #include "llvm/Support/Debug.h" #define DEBUG_TYPE "mlir" @@ -238,6 +240,9 @@ struct InterfaceMethodInfo bool isConditional; int interfacePosIndex; int virtualIndex; + // a generic method (`map(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 @@ -783,6 +788,10 @@ struct ClassInfo llvm::SmallVector 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 erasedGenericMethods; + llvm::SmallVector accessors; llvm::SmallVector indexes; diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 4c1b74e44..f8101ce52 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -1743,10 +1743,106 @@ namespace mlirgen return generate(); } + mlir::Type MLIRGenImpl::instantiateErasedGenericResultType(mlir::Location location, SignatureDeclarationBase signature, + mlir::Type thisType, NodeArray typeArguments, + SmallVector &operands, + const GenContext &genContext) + { + llvm::SmallVector 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 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 typeArguments, SmallVector &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 `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; diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index cb4009957..4a040b377 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -2804,6 +2804,71 @@ genContext); return mlir::failure(); } + std::pair 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, @@ -3016,6 +3081,18 @@ genContext); }, [&](std::string name, mlir_ts::FunctionType funcType, bool isConditional, int interfacePosIndex) -> std::pair { 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 @@ -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 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 typeParameters; if (mlir::failed( processTypeParameters(funcLikeDeclaration->typeParameters, typeParameters, genContext))) diff --git a/tslang/lib/TypeScript/MLIRGenGenerics.cpp b/tslang/lib/TypeScript/MLIRGenGenerics.cpp index ef228c078..b8df0f3b9 100644 --- a/tslang/lib/TypeScript/MLIRGenGenerics.cpp +++ b/tslang/lib/TypeScript/MLIRGenGenerics.cpp @@ -995,6 +995,60 @@ namespace mlirgen return mlir::success(); } + std::tuple 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 MLIRGenImpl::instantiateSpecializedFunction( mlir::Location location, StringRef name, NodeArray typeArguments, bool skipThisParam, SmallVector &operands, const GenContext &genContext) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index bd8c41c3c..5dd91dce8 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -1638,6 +1638,16 @@ class MLIRGenImpl mlir::Location location, StringRef name, NodeArray typeArguments, bool skipThisParam, SmallVector &operands, const GenContext &genContext); + // The generic function (a class's generic method) `name` instantiated with `any` for each of its + // type parameters: what fills an interface's slot for a generic method + std::tuple instantiateErasedGenericFunction( + mlir::Location location, StringRef name, const GenContext &genContext); + + // The generic method `name` of a class (or of its nearest base) instantiated with `any`; null when it + // has none + std::pair findErasedGenericMethod(mlir::Location location, ClassInfo::TypePtr classInfo, + mlir::StringRef name, const GenContext &genContext); + std::pair getFuncArgTypesOfGenericMethod( FunctionLikeDeclarationBase functionLikeDeclarationAST, ArrayRef typeParams, bool discoverReturnType, const GenContext &genContext); @@ -9367,6 +9377,16 @@ class MLIRGenImpl return value; } + // the interface methods a call is yet to be made through that are generic, erased to `any` + // (InterfaceMethodInfo::genericSignature): the call unboxes its result (mlirGenCallExpression) + llvm::DenseMap erasedGenericCallees; + + // The result type of a call of the generic interface method `signature` for its type arguments: given, + // or inferred from the arguments. Null when they can't be had: the call's result stays `any`. + mlir::Type instantiateErasedGenericResultType(mlir::Location location, SignatureDeclarationBase signature, + mlir::Type thisType, NodeArray typeArguments, + SmallVector &operands, const GenContext &genContext); + // see InterfaceFieldAccess's vtableOffset doc comment above. mlir::Value InterfaceMethodAccess(mlir::Location location, mlir::Value interfaceValue, InterfaceMethodInfo *methodInfo, int vtableOffset = 0) { @@ -9378,6 +9398,10 @@ class MLIRGenImpl auto interfaceSymbolRefValue = builder.create( location, effectiveFuncType, interfaceValue, builder.getI32IntegerAttr(vtableIndex), builder.getStringAttr(methodInfo->name), builder.getBoolAttr(methodInfo->isConditional)); + if (methodInfo->genericSignature) + { + erasedGenericCallees[interfaceSymbolRefValue.getOperation()] = methodInfo->genericSignature; + } return interfaceSymbolRefValue; } @@ -14387,7 +14411,8 @@ class MLIRGenImpl mlir::LogicalResult addInterfaceMethod(mlir::Location location, InterfaceInfo::TypePtr newInterfacePtr, llvm::SmallVector &methodInfos, StringRef methodName, mlir_ts::FunctionType funcType, bool isConditional, - int orderWeight, bool declareInterface, const GenContext &genContext) + int orderWeight, bool declareInterface, const GenContext &genContext, + SignatureDeclarationBase genericSignature = SignatureDeclarationBase()) { if (methodName.empty()) { @@ -14414,12 +14439,14 @@ class MLIRGenImpl if (methodIndex == -1) { methodInfos.push_back( - {methodName.str(), funcType, isConditional, orderWeight, newInterfacePtr->getNextVTableMemberIndex()}); + {methodName.str(), funcType, isConditional, orderWeight, newInterfacePtr->getNextVTableMemberIndex(), + genericSignature}); } else { methodInfos[methodIndex].funcType = funcType; methodInfos[methodIndex].isConditional = isConditional; + methodInfos[methodIndex].genericSignature = genericSignature; } return mlir::success(); @@ -14436,16 +14463,54 @@ class MLIRGenImpl methodNameOut = methodName; propertyNameOut = propertyName; - if (methodSignature->typeParameters.size() > 0) - { - emitError(location) << "Generic method '" << methodName << "' in the interface is not allowed"; - return mlir::failure(); - } - auto funcGenContext = GenContext(genContext); funcGenContext.clearScopeVars(); funcGenContext.thisType = interfaceType; + // a generic method is one slot erased to `any` for each type parameter: whatever implements it + // fills the slot with its method instantiated so, and a call boxes its arguments and unboxes the + // result to its type arguments (InterfaceGenericMethodCall) + if (methodSignature->typeParameters.size() > 0) + { + llvm::SmallVector typeParams; + if (mlir::failed(processTypeParameters(methodSignature->typeParameters, typeParams, genContext))) + { + return mlir::failure(); + } + + // ...a whole parameter or result only: `T[]` erased is `any[]`, whose elements are not laid out + // as a `number[]`'s, and no cast between them can be made + GenContext templateGenContext(funcGenContext); + for (auto &typeParam : typeParams) + { + templateGenContext.typeParamsWithArgs[typeParam->getName()] = + std::make_pair(typeParam, getNamedGenericType(typeParam->getName())); + } + + auto [templateProto, templateType, templateResults] = + mlirGenFunctionSignaturePrototype(methodSignature, true, templateGenContext); + if (!templateType) + { + return mlir::failure(); + } + + auto erasable = [&](mlir::Type type) { + return isa(type) || !mth.isGenericType(type); + }; + if (!llvm::all_of(templateType.getInputs(), erasable) || !llvm::all_of(templateType.getResults(), erasable)) + { + emitError(location) << "generic method '" << methodName + << "' in an interface: a type parameter can only be the whole type of a parameter " + "or of the result, not part of one ('T[]', '[A, B]', 'Box')"; + return mlir::failure(); + } + + for (auto &typeParam : typeParams) + { + funcGenContext.typeParamsWithArgs[typeParam->getName()] = std::make_pair(typeParam, getAnyType()); + } + } + auto res = mlirGenFunctionSignaturePrototype(methodSignature, true, funcGenContext); auto funcType = std::get<1>(res); funcTypeOut = funcType; @@ -15496,6 +15561,33 @@ class MLIRGenImpl declExports << ss.str().str(); } + void addInterfaceSourceToExport(InterfaceInfo::TypePtr interfaceInfo, InterfaceDeclaration interfaceDeclarationAST) + { + if (isAddedToExport(interfaceInfo->interfaceType)) + { + return; + } + + // re-declared from another module's embedded declarations: not this file's text + auto declEnd = static_cast(interfaceDeclarationAST->_end); + if (declEnd > sourceFile->text.length()) + { + return; + } + + exportedTypes.insert(interfaceInfo->interfaceType); + addDependancyTypesToExport(interfaceInfo->interfaceType); + + auto declText = convertWideToUTF8(getTextOfNodeFromSourceText(sourceFile->text, interfaceDeclarationAST.as(), true)); + + SmallVector out; + llvm::raw_svector_ostream ss(out); + MLIRDeclarationPrinter dp(ss, classSpecializationNamer()); + dp.printGenericClass(interfaceInfo->elementNamespace, declText); + + genericDeclExports << ss.str().str(); + } + void addEnumDeclarationToExport(StringRef name, NamespaceInfo::TypePtr elementNamespace, mlir_ts::EnumType enumType) { if (isAddedToExport(enumType)) diff --git a/tslang/lib/TypeScript/MLIRGenInterfaces.cpp b/tslang/lib/TypeScript/MLIRGenInterfaces.cpp index 8eb6ace53..610a4adcd 100644 --- a/tslang/lib/TypeScript/MLIRGenInterfaces.cpp +++ b/tslang/lib/TypeScript/MLIRGenInterfaces.cpp @@ -1399,7 +1399,16 @@ namespace mlirgen // add to export if any if (auto hasExport = getExportModifier(interfaceDeclarationAST)) { - addInterfaceDeclarationToExport(newInterfacePtr); + // a generic method prints as its slot, erased to `any`: the importer would call it without + // unboxing, so the interface goes as its source, as a generic interface does + if (llvm::any_of(newInterfacePtr->methods, [](auto &method) { return !!method.genericSignature; })) + { + addInterfaceSourceToExport(newInterfacePtr, interfaceDeclarationAST); + } + else + { + addInterfaceDeclarationToExport(newInterfacePtr); + } } return mlir::success(); @@ -1541,7 +1550,8 @@ namespace mlirgen } if (mlir::failed(addInterfaceMethod(location, newInterfacePtr, methodInfos, - methodName, funcType, isConditional, orderWeight, declarationMode, genContext))) + methodName, funcType, isConditional, orderWeight, declarationMode, genContext, + methodSignature->typeParameters.size() > 0 ? SignatureDeclarationBase(methodSignature) : SignatureDeclarationBase()))) { return mlir::failure(); } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 138d7d5ff..f4c8977f9 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-interface-generic-method COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_generic_method.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-interface-generic-method COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_generic_method.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") @@ -1634,6 +1636,7 @@ tslang_add_test(NAME test-compile-export-import-class-accessor COMMAND test-runn tslang_add_test(NAME test-compile-export-import-class-indexer COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_indexer.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_indexer.ts") 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-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") @@ -1824,6 +1827,7 @@ tslang_add_test(NAME test-compile-shared-export-import-class-static COMMAND test # implicitly inherited the replaced terminator's (also wrong) location instead of the function's # 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-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 @@ -1921,6 +1925,7 @@ tslang_add_test(NAME test-jit-shared-export-import-class-extends-implements-diam tslang_add_test(NAME test-jit-shared-export-import-class-abstract COMMAND test-runner -jit -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_class_abstract.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_class_abstract.ts") 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-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). @@ -4022,7 +4027,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_generator_this_param own_copy_within_returned_param own_swap_elements own_callback_forwarded own_optional_record_read own_param_default_kept own_literal_into_array own_generator_take own_rest_array_borrows own_string_copies - own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures + own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures own_interface_generic_method own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot) tslang_add_test(NAME test-jit-own-${own_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") @@ -4060,7 +4065,7 @@ foreach(keeps_mm rc gc none) own_copy_within_returned_param own_swap_elements own_callback_forwarded own_optional_record_read own_param_default_kept own_literal_into_array own_generator_take own_rest_array_borrows own_string_copies - own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures + own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures own_interface_generic_method own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot) tslang_add_test(NAME test-jit-${keeps_mm}-${keeps_test} COMMAND test-runner -jit -mm=${keeps_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${keeps_test}.ts") diff --git a/tslang/test/tester/own/own_interface_generic_method.ts b/tslang/test/tester/own/own_interface_generic_method.ts new file mode 100644 index 000000000..e3fd0e09a --- /dev/null +++ b/tslang/test/tester/own/own_interface_generic_method.ts @@ -0,0 +1,62 @@ +// Generic interface methods (erased `any` slots) under every model: an object given through `map` +// comes back as the caller's, unboxed from the `any` the slot returns, and a string argument beside a +// generic one is borrowed. Each step churns, so anything freed too early reads garbage. +interface Mapper { + map(x: T): T; + tag(x: T, label: string): string; +} + +class Box { + constructor(public n: number) {} +} + +class Id implements Mapper { + map(x: T): T { + return x; + } + + tag(x: T, label: string): string { + return "id:" + label; + } +} + +function churn() { + const junk: Box[] = []; + for (let i = 0; i < 64; i++) junk.push(new Box(999)); +} + +function use(m: Mapper, i: number) { + return m.map(i) + 1; +} + +function test(m: Mapper, i: number) { + let s: number = 0; + const b = m.map(new Box(i)); + churn(); + s += b.n; + + const label = "l" + i; + if (m.tag(i, label) == "id:l" + i) s += 1; + churn(); + if (label.length > 1) s += 1; + + const t = m.map("t" + i); + churn(); + s += t.length; + + s += use(m, i); + return s; +} + +function main() { + const m: Mapper = new Id(); + let ok = 0; + for (let i = 0; i < 300; i++) { + // i, 1, 1, ("t" + i).length, i + 1 + if (test(m, i) == 2 * i + 3 + ("t" + i).length) ok++; + churn(); + } + + assert(ok == 300, "ok"); + print("done."); +} diff --git a/tslang/test/tester/tests/00interface_generic_method.ts b/tslang/test/tester/tests/00interface_generic_method.ts new file mode 100644 index 000000000..32b5be553 --- /dev/null +++ b/tslang/test/tester/tests/00interface_generic_method.ts @@ -0,0 +1,87 @@ +// Generic methods in an interface: each is one vtable slot erased to `any` for its type parameters. +// A class fills it with its generic method instantiated with `any`; a call boxes the arguments and +// unboxes the result to the type its type arguments - given or inferred - make it. +interface Mapper { + map(x: T): T; + tag(x: T, label: string): string; + choose(a: A, b: A, first: boolean): A; +} + +class Box { + constructor(public n: number) {} +} + +class Id implements Mapper { + map(x: T): T { + return x; + } + + tag(x: T, label: string): string { + return "id:" + label; + } + + choose(a: A, b: A, first: boolean): A { + if (first) return a; + return b; + } +} + +class Logged implements Mapper { + count = 0; + + map(x: T): T { + this.count++; + return x; + } + + tag(x: T, label: string): string { + this.count++; + return "logged:" + label; + } + + choose(a: A, b: A, first: boolean): A { + this.count++; + if (first) return a; + return b; + } +} + +// inherits its generic methods from Id +class Sub extends Id { + extra() { + return 1; + } +} + +function use(m: Mapper) { + return m.map(40) + 2; +} + +function main() { + const m: Mapper = new Id(); + const n: number = m.map(5); + assert(n + 1 == 6, "explicit"); + + const s = m.map("ab"); + assert(s.length == 2, "inferred string"); + + const b = m.map(new Box(7)); + assert(b.n == 7, "class object"); + + assert(m.tag(1, "x") == "id:x", "non-generic result"); + + const c = m.choose("zero", "one", false); + assert(c == "one", "two parameters of one type"); + + const l = new Logged(); + const lm: Mapper = l; + assert(lm.map(3) == 3 && lm.tag("q", "y") == "logged:y", "another implementer"); + assert(l.count == 2, "its own state"); + + assert(use(new Id()) == 42 && use(l) == 42 && use(new Sub()) == 42, "dispatched"); + + // a call on the class itself is instantiated for its type arguments, as before + assert(new Id().map(8) == 8, "direct"); + + print("done."); +} diff --git a/tslang/test/tester/tests/export_interface_generic_method.ts b/tslang/test/tester/tests/export_interface_generic_method.ts new file mode 100644 index 000000000..1ce7f89c2 --- /dev/null +++ b/tslang/test/tester/tests/export_interface_generic_method.ts @@ -0,0 +1,25 @@ +namespace M { + + // An interface with generic methods (erased to `any` slots) and a class implementing it, both in + // the exporting module: the importer calls through the interface with its own type arguments, + // implements the interface itself, and gives its own objects to the exported function. + + export interface Mapper { + map(x: T): T; + tag(x: T, label: string): string; + } + + export class Id implements Mapper { + map(x: T): T { + return x; + } + + tag(x: T, label: string): string { + return "id:" + label; + } + } + + export function useMapper(m: Mapper): number { + return m.map(40) + 2; + } +} diff --git a/tslang/test/tester/tests/import_interface_generic_method.ts b/tslang/test/tester/tests/import_interface_generic_method.ts new file mode 100644 index 000000000..bd2a8e1c4 --- /dev/null +++ b/tslang/test/tester/tests/import_interface_generic_method.ts @@ -0,0 +1,29 @@ +import './export_interface_generic_method' + +class Upper implements M.Mapper { + map(x: T): T { + return x; + } + + tag(x: T, label: string): string { + return "upper:" + label; + } +} + +function main() { + const m: M.Mapper = new M.Id(); + const n: number = m.map(5); + assert(n + 1 == 6, "number"); + const s = m.map("ab"); + assert(s.length == 2, "string"); + assert(m.tag(1, "x") == "id:x", "tag"); + + const u: M.Mapper = new Upper(); + assert(u.map(7) == 7, "local implementer"); + assert(u.tag(true, "y") == "upper:y", "local tag"); + + assert(M.useMapper(m) == 42, "exported function, exported class"); + assert(M.useMapper(u) == 42, "exported function, local class"); + + print("done."); +}