From c7a6be20c6638b25aa7dd710faeefa859119ed47 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 14:52:29 +0000 Subject: [PATCH 1/4] `in` and `instanceof` on a union of interfaces `"swim" in a` for `a: Fish | Bird` was "not supported", and `a instanceof Fish` was always false (the types compared, `Fish | Bird` against `Fish`). Every interface's union tag reads "interface", so nothing at run time said which interface the union held. Which members have the key, or are the interface, is decided when compiling: every one or none folds to a constant. Otherwise the union's tag is asked: an interface's descriptor now has an id of its name in TYPE_DESCR_LAYOUT, and ts.IsTypeTagOf compares a tag's with a type's. `"k" in a` narrows `a` to the members with the key (and the `else` to the others), as `instanceof` already narrowed. Test: 00in_interface_union (compile and JIT; gc, rc, none, own). Co-Authored-By: Claude Opus 5.5 --- tslang/include/TypeScript/Defines.h | 3 +- .../TypeScript/MLIRLogic/TypeOfOpHelper.h | 22 ++-- tslang/include/TypeScript/TypeScriptOps.td | 12 ++ tslang/lib/TypeScript/LowerToAffineLoops.cpp | 2 +- tslang/lib/TypeScript/LowerToLLVM.cpp | 23 +++- tslang/lib/TypeScript/MLIRGenImpl.h | 105 +++++++++++++++++- .../TypeScript/OwnershipInferenceMoves.cpp | 2 +- tslang/test/tester/CMakeLists.txt | 3 + .../test/tester/tests/00in_interface_union.ts | 83 ++++++++++++++ 9 files changed, 241 insertions(+), 14 deletions(-) create mode 100644 tslang/test/tester/tests/00in_interface_union.ts diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index e34a5bca4..3084f5b9b 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -489,7 +489,8 @@ // the block header, which has to stay last - see TYPE_DESCR_BLOCK_HEADER. #define TYPE_DESCR_KIND 0 // For a tuple, an id of its layout - its fields' names and types (TypeOfOpHelper::layoutIdOf) - -// and 0 for anything else. A cast from `any` to an object type compares it with the type's own +// for an interface, an id of its name (which interface a union of interfaces holds, every one's tag +// being "interface": ts.IsTypeTagOf), and 0 for anything else. A cast from `any` to an object type compares it with the type's own // (ts.IsTupleOfLayout): the box says only "tuple", and a tuple of other fields read as the type's // was garbage (`{ n: 5 }` holds an s32, read as a number). Computed from the type's text, so a // tuple boxed by one module matches the same type in another. diff --git a/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h b/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h index 1c46a2a74..6c9e87bc2 100644 --- a/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h @@ -142,19 +142,27 @@ class TypeOfOpHelper os << "}"; } - // TYPE_DESCR_LAYOUT of a type's descriptor: an id of a tuple's layout text (never 0), and 0 for - // anything else. A hash of the text, not of the type: the type's own hash differs between - // modules, which a tuple boxed in one and cast in another must not. + // TYPE_DESCR_LAYOUT of a type's descriptor: an id of a tuple's layout text, or of an interface's + // name (never 0), and 0 for anything else. A hash of the text, not of the type: the type's own + // hash differs between modules, which a tuple boxed in one and cast in another must not, nor an + // interface a union holds. static uint32_t layoutIdOf(mlir::Type type) { - if (!isa(type)) + std::string text; + llvm::raw_string_ostream os(text); + if (auto interfaceType = dyn_cast(type)) + { + os << "interface " << interfaceType.getName().getValue(); + } + else if (isa(type)) + { + layoutText(type, os); + } + else { return 0; } - std::string text; - llvm::raw_string_ostream os(text); - layoutText(type, os); auto id = (uint32_t)llvm::xxh3_64bits(os.str()); return id ? id : 1; } diff --git a/tslang/include/TypeScript/TypeScriptOps.td b/tslang/include/TypeScript/TypeScriptOps.td index 94baea315..57b5ff232 100644 --- a/tslang/include/TypeScript/TypeScriptOps.td +++ b/tslang/include/TypeScript/TypeScriptOps.td @@ -513,6 +513,18 @@ def TypeScript_IsTupleOfLayoutOp : TypeScript_Op<"IsTupleOfLayout", [Pure]> { let results = (outs TypeScript_Boolean:$res); } +def TypeScript_IsTypeTagOfOp : TypeScript_Op<"IsTypeTagOf", [Pure]> { + let summary = "whether a type tag names an interface"; + let description = [{ + True when $tag (a union's type tag, ts.GetTypeInfoFromUnionOp) names $type: the TYPE_DESCR_LAYOUT + of its descriptor is $type's. Every interface's tag reads "interface"; its descriptor says which + (`"swim" in a`, `a instanceof Fish` for `a: Fish | Bird`). + }]; + + let arguments = (ins TypeScript_String:$tag, TypeAttr:$type); + let results = (outs TypeScript_Boolean:$res); +} + def TypeScript_TypeDescriptorOp : TypeScript_Op<"TypeDescriptor", [Pure]> { let summary = "type name from the static descriptor of a type"; let description = [{ diff --git a/tslang/lib/TypeScript/LowerToAffineLoops.cpp b/tslang/lib/TypeScript/LowerToAffineLoops.cpp index 2414d6fe6..5cfa0751f 100644 --- a/tslang/lib/TypeScript/LowerToAffineLoops.cpp +++ b/tslang/lib/TypeScript/LowerToAffineLoops.cpp @@ -2971,7 +2971,7 @@ void AddTsAffineLegalOps(ConversionTarget &target) mlir_ts::EndCatchOp, mlir_ts::BeginCleanupOp, mlir_ts::EndCleanupOp, mlir_ts::ThrowUnwindOp, mlir_ts::ThrowCallOp, mlir_ts::SymbolCallInternalOp, mlir_ts::CallInternalOp, mlir_ts::ReturnInternalOp, mlir_ts::NoOp, mlir_ts::SwitchStateInternalOp, mlir_ts::UnreachableOp, mlir_ts::GlobalConstructorOp, mlir_ts::AppendToUsedOp, - mlir_ts::CreateBoundFunctionOp, mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp, mlir_ts::BoxOp, mlir_ts::UnboxOp, + mlir_ts::CreateBoundFunctionOp, mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp, mlir_ts::IsTypeTagOfOp, mlir_ts::BoxOp, mlir_ts::UnboxOp, mlir_ts::CreateUnionInstanceOp, mlir_ts::GetValueFromUnionOp, mlir_ts::GetTypeInfoFromUnionOp, mlir_ts::OptionalOp, mlir_ts::OptionalValueOp, mlir_ts::OptionalUndefOp, mlir_ts::LoadLibraryPermanentlyOp, mlir_ts::SearchForAddressOfSymbolOp, diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 6c54b8d82..2bff8db12 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -7852,6 +7852,27 @@ struct IsTupleOfLayoutOpLowering : public TsLlvmPattern +{ + using TsLlvmPattern::TsLlvmPattern; + + LogicalResult matchAndRewrite(mlir_ts::IsTypeTagOfOp op, Adaptor transformed, + ConversionPatternRewriter &rewriter) const final + { + auto loc = op.getLoc(); + + TypeHelper th(rewriter); + TypeConverterHelper tch(getTypeConverter()); + + TypeDescriptorLogic tdl(rewriter, tch, loc); + auto layout = tdl.getLayoutFromTag(transformed.getTag()); + auto expected = rewriter.create( + loc, th.getI32Type(), rewriter.getI32IntegerAttr((int32_t)TypeOfOpHelper::layoutIdOf(op.getType()))); + rewriter.replaceOpWithNewOp(op, LLVM::ICmpPredicate::eq, layout, expected); + return success(); + } +}; + struct TypeOfAnyOpLowering : public TsLlvmPattern { using TsLlvmPattern::TsLlvmPattern; @@ -9517,7 +9538,7 @@ void TypeScriptToLLVMLoweringPass::runOnOperation() LoadSaveValueLowering, ThrowUnwindOpLowering, ThrowCallOpLowering, VariableOpLowering, DebugVariableOpLowering, AllocaOpLowering, InvokeOpLowering, AccessorUnwindEdgeOpLowering, InvokeHybridOpLowering, VirtualSymbolRefOpLowering, ThisVirtualSymbolRefOpLowering, ThisSymbolRefOpLowering, InterfaceSymbolRefOpLowering, NewInterfaceOpLowering, VTableOffsetRefOpLowering, LoadBoundRefOpLowering, StoreBoundRefOpLowering, CreateBoundRefOpLowering, - CreateBoundFunctionOpLowering, GetThisOpLowering, GetMethodOpLowering, TypeOfOpLowering, TypeOfAnyOpLowering, IsTupleOfLayoutOpLowering, DebuggerOpLowering, + CreateBoundFunctionOpLowering, GetThisOpLowering, GetMethodOpLowering, TypeOfOpLowering, TypeOfAnyOpLowering, IsTupleOfLayoutOpLowering, IsTypeTagOfOpLowering, DebuggerOpLowering, UnreachableOpLowering, SymbolCallInternalOpLowering, CallInternalOpLowering, CallHybridInternalOpLowering, ReturnInternalOpLowering, NoOpLowering, GlobalConstructorOpLowering, AppendToUsedOpLowering, ExtractInterfaceThisOpLowering, ExtractInterfaceVTableOpLowering, BoxOpLowering, UnboxOpLowering, DialectCastOpLowering, CreateUnionInstanceOpLowering, diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 8f9613170..5f12f9806 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -5000,6 +5000,25 @@ class MLIRGenImpl return mlir::success(); } + // `"swim" in a` for `a: Fish | Bird`: `a` is the members that have the key + if (op == SyntaxKind::InKeyword && binExpr->right == SyntaxKind::Identifier && + (binExpr->left == SyntaxKind::StringLiteral || binExpr->left == SyntaxKind::NoSubstitutionTemplateLiteral)) + { + if (auto unionType = dyn_cast_or_null(evaluate(binExpr->right, genContext))) + { + auto key = builder.getStringAttr(convertWideToUTF8(binExpr->left.as()->text)); + SmallVector withKey; + if (interfacesWithKey(loc(binExpr), unionType, key, withKey) && !withKey.empty() && + withKey.size() < unionType.getTypes().size()) + { + auto safeType = withKey.size() == 1 ? withKey.front() : getUnionType(withKey); + return addSafeCastStatement(binExpr->right, safeType, false, elseSafeCase, genContext); + } + } + + return mlir::success(); + } + if (op == SyntaxKind::InstanceOfKeyword) { auto instanceOf = binExpr; @@ -6016,6 +6035,57 @@ class MLIRGenImpl return ifResult; } + // The members of a union of interfaces that have `key`, a field or a method; false when a member is + // not an interface, or the union has no tag to tell its members apart. + bool interfacesWithKey(mlir::Location location, mlir_ts::UnionType unionType, mlir::Attribute key, + SmallVectorImpl &withKey) + { + mlir::Type baseType; + if (!isa_and_nonnull(key) || !mth.isUnionTypeNeedsTag(location, unionType, baseType)) + { + return false; + } + + for (auto member : unionType.getTypes()) + { + auto interfaceType = dyn_cast(member); + if (!interfaceType) + { + return false; + } + + auto interfaceInfo = getInterfaceInfoByFullName(interfaceType.getName().getValue()); + if (!interfaceInfo) + { + return false; + } + + auto name = mlir::cast(key).getValue(); + if (interfaceInfo->getFieldIndex(key) >= 0 || interfaceInfo->getMethodIndex(name) >= 0) + { + withKey.push_back(member); + } + } + + return true; + } + + // Whether a tagged union holds one of `members`: its tag names one of them (ts.IsTypeTagOf). + ValueOrLogicalResult mlirGenUnionHoldsOneOf(mlir::Location location, mlir::Value unionValue, ArrayRef members) + { + auto tag = builder.create(location, getStringType(), unionValue); + mlir::Value holds; + for (auto member : members) + { + mlir::Value isMember = builder.create(location, getBooleanType(), tag, mlir::TypeAttr::get(member)); + holds = holds ? builder.create( + location, getBooleanType(), builder.getI32IntegerAttr((int)SyntaxKind::BarBarToken), holds, isMember) + : isMember; + } + + return holds; + } + ValueOrLogicalResult mlirGenInLogic(BinaryExpression binaryExpressionAST, const GenContext &genContext) { // Supports only array now @@ -6070,10 +6140,24 @@ class MLIRGenImpl return mlir::failure(); } - if (isa(rightExpressionValue.getType())) + if (auto unionType = dyn_cast(rightExpressionValue.getType())) { - emitError(loc(binaryExpressionAST->right), "not supported"); - return mlir::failure(); + // a union of interfaces: which members have the key is known here, and which member the + // value holds is asked of its tag only when some have it and some do not + auto constantOp = leftExpressionValue.getDefiningOp(); + SmallVector withKey; + if (!constantOp || !interfacesWithKey(location, unionType, constantOp.getValue(), withKey)) + { + emitError(loc(binaryExpressionAST->right), "not supported"); + return mlir::failure(); + } + + if (withKey.empty() || withKey.size() == unionType.getTypes().size()) + { + return mlirGenBooleanValue(location, !withKey.empty()); + } + + return mlirGenUnionHoldsOneOf(location, rightExpressionValue, withKey); } if (auto constantOp = leftExpressionValue.getDefiningOp()) @@ -6493,6 +6577,21 @@ class MLIRGenImpl } #endif + // `a instanceof Fish` for `a: Fish | Bird`: which interface the union holds is its tag's (every + // one's reads "interface") + if (auto unionType = dyn_cast(resultLeftfType); unionType && isa(rightType)) + { + mlir::Type baseType; + if (llvm::is_contained(unionType.getTypes(), rightType) && mth.isUnionTypeNeedsTag(location, unionType, baseType)) + { + auto refType = dyn_cast(resultLeftValue.getType()); + auto leftValue = refType + ? builder.create(location, refType.getElementType(), resultLeftValue).getResult() + : resultLeftValue; + return mlirGenUnionHoldsOneOf(location, leftValue, {rightType}); + } + } + LLVM_DEBUG(llvm::dbgs() << "!! instanceOf precalc value: " << (resultLeftfType == rightType) << " '" << resultLeftfType << "' is '" << rightType << "'\n";); diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index da3627284..e9d7b0402 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -428,7 +428,7 @@ namespace own_inference // a test - `if (d)`, `d?.x`, `typeof u` - asks about the value, and keeps nothing if (mlir::isa(user)) + mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp, mlir_ts::IsTypeTagOfOp>(user)) { return true; } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index ce1408881..56302ada8 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -740,6 +740,7 @@ tslang_add_test(NAME test-compile-00-try-finally COMMAND test-runner "${PROJECT_ tslang_add_test(NAME test-compile-00-try-finally-throws COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_throws.ts") 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-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") tslang_add_test(NAME test-compile-00-try-finally-funclet COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_funclet.ts") @@ -1368,6 +1369,7 @@ tslang_add_test(NAME test-jit-00-try-finally COMMAND test-runner -jit "${PROJECT tslang_add_test(NAME test-jit-00-try-finally-throws COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_throws.ts") 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-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") tslang_add_test(NAME test-jit-00-try-finally-funclet COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_funclet.ts") @@ -2490,6 +2492,7 @@ set(TSLANG_CORPUS 00try_finally_throws.ts 00function_fewer_parameters.ts 00closure_fewer_parameters.ts + 00in_interface_union.ts 00try_using_catch.ts 00tuple_named.ts 00tuple_with_array.ts diff --git a/tslang/test/tester/tests/00in_interface_union.ts b/tslang/test/tester/tests/00in_interface_union.ts new file mode 100644 index 000000000..ea13ddbd3 --- /dev/null +++ b/tslang/test/tester/tests/00in_interface_union.ts @@ -0,0 +1,83 @@ +// `"k" in a` and `a instanceof I` for a union of interfaces. Which members have the key, or are the +// interface, is known when compiling; which member the value holds is asked of the union's tag, which +// says "interface" for every one but whose descriptor names which. `in` narrows the value to the members +// with the key, and the `else` to the others. Before, `in` on a union was "not supported" and +// `a instanceof Fish` was always false. +interface Fish { + swim(): string; +} + +interface Bird { + fly(): string; +} + +interface Duck { + swim(): string; + fly(): string; + quack(): string; +} + +class Salmon implements Fish { + swim() { return "swims"; } +} + +class Crow implements Bird { + fly() { return "flies"; } +} + +class Mallard implements Duck { + swim() { return "paddles"; } + fly() { return "flaps"; } + quack() { return "quacks"; } +} + +function move(a: Fish | Bird) { + if ("swim" in a) { + return a.swim(); + } else { + return a.fly(); + } +} + +function moveAll(a: Fish | Bird | Duck) { + if ("quack" in a) { + return a.quack(); + } + + if ("swim" in a) { + return "swim:" + a.swim(); + } + + return "fly"; +} + +function kind(a: Fish | Bird) { + if (a instanceof Fish) { + return "fish"; + } + + return "bird"; +} + +function main() { + const f: Fish = new Salmon(); + const b: Bird = new Crow(); + const d: Duck = new Mallard(); + + assert(move(f) == "swims"); + assert(move(b) == "flies"); + + assert(moveAll(f) == "swim:swims"); + assert(moveAll(b) == "fly"); + assert(moveAll(d) == "quacks"); + + assert(kind(f) == "fish"); + assert(kind(b) == "bird"); + + // a key every member has, or none: decided when compiling + const both: Fish | Duck = d; + assert("swim" in both); + assert(!("bark" in both)); + + print("done."); +} From df0f625bf0435879c8204ba298aad208f10620bc Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 15:28:25 +0000 Subject: [PATCH 2/4] An object literal or class object given to a union of interfaces `move({ swim: () => "s" })` for `move(a: Fish | Bird)` failed with "'ts.Cast' op type [...] can't be stored in [...]", and so did a class object. castToTaggedUnionType now casts such a value to the first interface member whose every required field and method it has (interfaceMemberFitting, by name, as `"k" in v` asks), and the union's tag says which (`"swim" in a`, #737). Test: 00interface_union_literal (compile and JIT; gc, rc, none, own). Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenCast.cpp | 62 +++++++++++++++++++ tslang/lib/TypeScript/MLIRGenImpl.h | 2 + tslang/test/tester/CMakeLists.txt | 3 + .../tester/tests/00interface_union_literal.ts | 28 +++++++++ 4 files changed, 95 insertions(+) create mode 100644 tslang/test/tester/tests/00interface_union_literal.ts diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index a6e8008ab..ffbda6989 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -1758,6 +1758,59 @@ namespace mlirgen return std::nullopt; } + // The first interface member of a union whose every required field and method an object literal, a + // tuple or a class object has, by name; null for another value or when none fits. + mlir::Type MLIRGenImpl::interfaceMemberFitting(mlir_ts::UnionType unionType, mlir::Type valueType) + { + if (!isa(valueType)) + { + return mlir::Type(); + } + + // a field or a method of that name, as `"k" in v` asks of one value (mlirGenInLogic) + auto has = [&](mlir::Attribute id) { return !!mth.getFieldTypeByFieldName(valueType, id); }; + + std::function fits = [&](InterfaceInfo::TypePtr interfaceInfo) { + for (auto &extent : interfaceInfo->extends) + { + if (!fits(std::get<1>(extent))) + { + return false; + } + } + + for (auto &method : interfaceInfo->methods) + { + if (!method.isConditional && !has(builder.getStringAttr(method.name))) + { + return false; + } + } + + for (auto &field : interfaceInfo->fields) + { + if (!field.isConditional && !has(field.id)) + { + return false; + } + } + + return true; + }; + + for (auto member : unionType.getTypes()) + { + auto interfaceType = dyn_cast(member); + auto interfaceInfo = interfaceType ? getInterfaceInfoByFullName(interfaceType.getName().getValue()) : InterfaceInfo::TypePtr(); + if (interfaceInfo && fits(interfaceInfo)) + { + return member; + } + } + + return mlir::Type(); + } + std::optional MLIRGenImpl::castToTaggedUnionType(mlir::Location location, mlir::Type type, mlir::Value value, mlir::Type valueType, const GenContext &genContext) { if (auto unionType = dyn_cast(type)) @@ -1778,6 +1831,15 @@ namespace mlirgen } } + // an object literal, a tuple or a class object given to a union of interfaces + // (`move({ swim: () => "s" })` for `Fish | Bird`): it becomes the first interface it has every member of, and the + // union's tag says which (`"swim" in a`) + if (auto memberType = interfaceMemberFitting(unionType, valueType)) + { + CAST(value, location, memberType, value, genContext); + return V(builder.create(location, type, value)); + } + // one member and null (`{ k: number } | null`): what is not null is that member - // an object literal `{ k: 5 }`, whose field is an s32, is converted to it if (!isa(valueType) && types.size() == 2 diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 5f12f9806..bd8c41c3c 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -14722,6 +14722,8 @@ class MLIRGenImpl // reports which part of a function signature does not match the one it is assigned to void emitFunctionTypeMismatch(mlir::Location location, mlir::Type valueType, mlir::Type type, MatchResult match); + mlir::Type interfaceMemberFitting(mlir_ts::UnionType unionType, mlir::Type valueType); + mlir::Value fewerParametersThunk(mlir::Location location, mlir::Value value, mlir::Type type); // optional diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 56302ada8..d6d877e39 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-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") tslang_add_test(NAME test-compile-00-try-finally-funclet COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_funclet.ts") @@ -1370,6 +1371,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-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") tslang_add_test(NAME test-jit-00-try-finally-funclet COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_funclet.ts") @@ -2493,6 +2495,7 @@ set(TSLANG_CORPUS 00function_fewer_parameters.ts 00closure_fewer_parameters.ts 00in_interface_union.ts + 00interface_union_literal.ts 00try_using_catch.ts 00tuple_named.ts 00tuple_with_array.ts diff --git a/tslang/test/tester/tests/00interface_union_literal.ts b/tslang/test/tester/tests/00interface_union_literal.ts new file mode 100644 index 000000000..313a08ed1 --- /dev/null +++ b/tslang/test/tester/tests/00interface_union_literal.ts @@ -0,0 +1,28 @@ +// An object literal, a literal held by a const, or a class object given to a union of interfaces becomes +// the first interface it has every member of, and the union's tag says which: `"swim" in a` then tells +// them apart. A literal was "can't be stored in" the union (a compiler error), and so was a class object. +interface Fish { + swim(): string; +} + +interface Bird { + fly(): string; +} + +class Crow implements Bird { + fly() { return "fly"; } +} + +function move(a: Fish | Bird) { + return "swim" in a ? a.swim() : a.fly(); +} + +function main() { + const k = "!"; + assert(move({ swim: () => "s" }) == "s"); + assert(move({ fly: () => "f" + k }) == "f!"); + const o = { swim: () => "o" }; + assert(move(o) == "o"); + assert(move(new Crow()) == "fly"); + print("done."); +} From d10deb620471573dccb73fc6f0255ec2769d08a1 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 15:28:32 +0000 Subject: [PATCH 3/4] Fewer-parameter callbacks: generic inference and a thunk's owned result Two bugs in the fewer-parameters thunk (#733, #735), found by giving the default library's array callbacks an index parameter: - A closure given for a generic callback `(v: T, i: number) => void` had its captures paired with `T` (`string | Reference<{...}>`): its type is its function bound over its captures. Inference now drops the bound first parameter, of the closure's type and of the arrow type rebuilt. - Under -mm=own a heap result the thunk hands on (a string a `map` callback builds) was "a second reference": the thunk's call is now marked owned and consumed by its return, as `return f(x)` is. Test: 00closure_fewer_parameters (a generic callback, a string result). Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenCast.cpp | 8 ++++++++ tslang/lib/TypeScript/MLIRGenGenerics.cpp | 16 ++++++++++++++++ .../tests/00closure_fewer_parameters.ts | 19 +++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index ffbda6989..9ab561e33 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -2211,6 +2211,14 @@ namespace mlirgen entryBlock.getArguments().take_front(inInputs.size())); if (hasResult) { + // the callee's result is the thunk's, handed on as `return f(x)` hands it: owned, and + // taken over by the return (a string `map` builds came back as a second reference) + if (mth.ownsHeapMemory(noLocation, results.front())) + { + callOp->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + callOp->setAttr(OWNED_RESULT_CONSUMED_ATTR_NAME, builder.getUnitAttr()); + } + builder.create(noLocation, callOp.getResult(0), entryOp.getReference()); } diff --git a/tslang/lib/TypeScript/MLIRGenGenerics.cpp b/tslang/lib/TypeScript/MLIRGenGenerics.cpp index b6d355178..ef228c078 100644 --- a/tslang/lib/TypeScript/MLIRGenGenerics.cpp +++ b/tslang/lib/TypeScript/MLIRGenGenerics.cpp @@ -306,6 +306,14 @@ namespace mlirgen if (tempfuncType.size() > 0 || mth.getReturnsFromFuncRef(templateType).size() > 0) { auto funcType = mth.getParamsFromFuncRef(concreteType); + // a closure is its function bound over its captures, which its first parameter takes: not one + // the callback type has (`each(xs, (v) => { s += v; })` for `f: (v: T, i: number) => void` + // paired `T` with the captures) + if (isa(concreteType) && !funcType.empty()) + { + funcType = funcType.drop_front(); + } + if (funcType.size() > 0 || tempfuncType.size() == 0) { inferTypeFuncType(location, tempfuncType, funcType, results, genContext); @@ -792,6 +800,14 @@ namespace mlirgen return {mlir::failure(), true}; } + // ...and so does the arrow's type built again here + if (auto funcType = dyn_cast(newArrowFuncType); + funcType && argOp.getDefiningOp() && funcType.getNumInputs() > 0) + { + newArrowFuncType = mlir_ts::FunctionType::get(builder.getContext(), funcType.getInputs().drop_front(), + funcType.getResults(), funcType.isVarArg()); + } + // infer second type when ArrowType is fully built StringMap inferredTypes; inferType(location, paramType, newArrowFuncType, inferredTypes, genericTypeGenContext); diff --git a/tslang/test/tester/tests/00closure_fewer_parameters.ts b/tslang/test/tester/tests/00closure_fewer_parameters.ts index c936e6dd9..44c89167e 100644 --- a/tslang/test/tester/tests/00closure_fewer_parameters.ts +++ b/tslang/test/tester/tests/00closure_fewer_parameters.ts @@ -15,6 +15,16 @@ function apply(f: (a: number, b: number) => number) { return f(2, 3); } +function eachOf(xs: T[], f: (v: T, i: number) => void) { + for (let i = 0; i < xs.length; i++) f(xs[i], i); +} + +function mapOf(xs: T[], f: (v: T, i: number) => V) { + const result: V[] = []; + for (let i = 0; i < xs.length; i++) result.push(f(xs[i], i)); + return result; +} + function churn() { const junk: Box[] = []; for (let i = 0; i < 64; i++) junk.push(new Box(999)); @@ -39,5 +49,14 @@ function main() { each(["x", "y", "z"], () => { calls++; }); assert(calls == 3); + // a generic callback: the arrow's captures are not a parameter `T` is inferred from (it was + // `string | Reference<...>`) + let joined = ""; + eachOf(["p", "q"], (v) => { joined += v; }); + assert(joined == "pq"); + + // a result the thunk hands on owns its block (-mm=own took it for a second reference) + assert(mapOf(["m", "n"], (v) => v + "!")[1] == "n!"); + print("done."); } From 961fafa1d27ce9355979067cff35db4b7d78d888 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 15:28:33 +0000 Subject: [PATCH 4/4] Design notes: generic interface methods, classes as values - docs/generic-interface-methods-design.md: generic methods in interfaces (rejected today) and in class hierarchies (not virtual: an override is never reached through a base reference, silently). Options: erased `any` slots, a closed-world table, dictionary passing; recommends an error for overridden generic class methods now, erased slots later. - docs/classes-as-values-design.md: `typeof A` values (ts.ClassRef has no value lowering) and local classes that capture (members lifted with an extra parameter nobody passes). Recommends the vtable as the class value with a `.constructor` slot, and the captures in a hidden `.captured` field of the instance. - docs/tuple-object-shape-ambiguity-design.md: re-checked, still open. Co-Authored-By: Claude Opus 5.5 --- tslang/docs/classes-as-values-design.md | 97 +++++++++++++++++++ .../docs/generic-interface-methods-design.md | 78 +++++++++++++++ .../tuple-object-shape-ambiguity-design.md | 4 +- 3 files changed, 178 insertions(+), 1 deletion(-) create mode 100644 tslang/docs/classes-as-values-design.md create mode 100644 tslang/docs/generic-interface-methods-design.md diff --git a/tslang/docs/classes-as-values-design.md b/tslang/docs/classes-as-values-design.md new file mode 100644 index 000000000..9ee2a690c --- /dev/null +++ b/tslang/docs/classes-as-values-design.md @@ -0,0 +1,97 @@ +# Classes as values, and local classes that capture: design + +Status: **proposed, not implemented**. Written 2026-10-29, to be picked up later. + +## 1. What works and what fails today + +**Works:** a class used under another name at compile time. + +```ts +const C = A; // an alias: `new C(3)` is `new A(3)` +const D = class { v = 7; }; +``` + +**Fails:** a class passed or stored as a run-time value. + +```ts +function make(c: typeof A, n: number) { return new c(n); } +make(A, 1); make(B, 1); // B extends A +``` + +This fails with "failed to legalize operation 'ts.ClassRef' that was explicitly marked illegal". `ts.ClassRef` names a class at compile time only. No lowering turns it into a value, so a class given to a parameter, stored in a variable, an array or a field, or returned, has nothing to lower to. + +**Fails:** a class declared in a function whose members read the function's locals. + +```ts +function counter(start: number) { + class Counter { n = start; inc() { this.n += start; return this.n; } } + return new Counter(); +} +counter(2).inc(); // "Expected 1 arguments, but got 0." +``` + +The members are lifted to module functions that take the captured variables as an extra parameter, the way an arrow function's body does. A call through the object (`c.inc()`), or the field initializers run by `new`, never pass it. + +## 2. Classes as values + +### 2.1 Representation + +A class value is a pointer to the class's vtable. Every vtable already has the pieces a value needs: `.instanceOf`, `.new` (`NEW_METHOD_NAME`, allocation), `.rtti` and the methods. `typeof A` becomes a type, `ClassValueType`, lowered to that pointer. + +- **Assignability:** `B`'s value is assignable to `typeof A` when `B` extends `A` and its constructor accepts `A`'s arguments. TypeScript checks the construct signatures structurally; nominal "extends" plus a parameter check is enough here. +- **`ts.ClassRef` used as a value:** it becomes the address of the class's vtable (`ts.AddressOf @A..vtbl`), as the object constructor already stores it. + +### 2.2 Construction through a value + +`new c(n)` with `c: typeof A` takes three steps: +1. **Allocate:** call the vtable's `.new` slot. +2. **Construct:** call the constructor, which must be reachable from the vtable too. A new slot, `.constructor`, typed as `A`'s constructor; a subclass fills it with its own constructor, which takes the same arguments for an assignable class. +3. **Result:** the result type is `A`. + +Static members (`c.create()`, `c.count`) need slots of their own, or a second table the vtable points to. The first version can leave them out: report "static member through a class value is not supported". + +### 2.3 Ownership + +- **The class value owns nothing:** it points at static data, like a string literal. It is immortal under rc and own. +- **The constructed object:** it is a fresh owned result, like `new A(n)`. + +### 2.4 Cross-module + +A vtable of a class from a `-shared` library is already addressable (`isDynamicImport`), so a class value can refer to it. The new `.constructor` slot changes the vtable layout. Classes compiled by an older compiler would not have it, so the slot goes at the end, and the layout contract in `docs/interface-vtable-simplification-design.md` gains one entry. + +### 2.5 Tests + +- a factory that takes `typeof A` and is given `A` and a subclass; +- an array of class values; +- `instanceof` against a class value; +- under gc, rc, none and own. + +## 3. Local classes that capture + +### 3.1 Options + +**A. Captures in the instance.** The class's storage gains a hidden field, `.captured`, holding the capture box (as an object literal's `.captured` field does, `MLIRGenExpressions.cpp`). +- **Filling it:** `new Counter()` in the declaring function fills it from the current box. +- **Reading it:** members read the captured variables through `this..captured` instead of an extra parameter, so a call through the object passes nothing new. +- **Pros:** works for methods, accessors, field initializers and the constructor, and for an object that outlives the function (`return new Counter()`). + +**B. One class per declaring call.** Instantiate the class's functions again per capture box. That's impossible without run-time code generation. + +**C. Reject.** Report an error for a member of a local class that names a local of the enclosing function, instead of the misleading arity error. + +### 3.2 Recommendation + +1. **Now:** do C. It replaces "Expected 1 arguments, but got 0" with an error that names the captured variable. +2. **Then:** A. + - **Boxes are reused:** they're the same capture boxes arrow functions use (`ts.Capture`, `__capture_box`). + - **Under own:** the box is owned by the instance and freed with it. The instance's release routine releases `.captured`, the way a closure's box routine does (spec 2.5 in the own design document). + - **Under rc:** the box is counted like any other field. + +### 3.3 Interaction with classes as values + +A local class used as a value (`return Counter`) carries its captures. Its value then has to be a pair, `{vtable, box}`, not the vtable alone. Keep the two features apart at first: class values only for module-level classes, and an error for a local class that captures and is used as a 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. +- `typeof` on a class value returning `"function"` as in JavaScript: tslang's `typeof` reports its own kind names. Decide when class values land. diff --git a/tslang/docs/generic-interface-methods-design.md b/tslang/docs/generic-interface-methods-design.md new file mode 100644 index 000000000..403a9d422 --- /dev/null +++ b/tslang/docs/generic-interface-methods-design.md @@ -0,0 +1,78 @@ +# Generic methods in interfaces (and virtual generic class methods): design + +Status: **proposed, not implemented**. Written 2026-10-29, to be picked up later. + +## 1. What fails today + +```ts +interface Mapper { map(x: T): T; } +class Id implements Mapper { map(x: T): T { return x; } } +const m: Mapper = new Id(); +m.map(5); +``` + +- **The interface:** compiling it fails with "Generic method 'map' in the interface is not allowed". `getInterfaceMethodNameAndType` (`lib/TypeScript/MLIRGenImpl.h`) refuses any method signature with type parameters. +- **A class hierarchy, worse because it's silent:** + +```ts +class Id { map(x: T): T { return x; } } +class Twice extends Id { map(x: T): T { print("twice"); return x; } } +const a: Id = new Twice(); +a.map(5); // calls Id.map: "twice" is never printed +``` + +A generic class method is not virtual. Each call instantiates the method of the *static* type's class (`staticGenericMethods`, `MLIRGenClasses.cpp`), so an override in a subclass is never reached through a base reference. No error or warning says so. + +## 2. Why it is not simply a vtable slot + +A vtable slot holds one function pointer. A generic method has no single function, only one instantiation per type argument, and each is produced where a call names it (monomorphization). + +- **Through an interface or a base class:** the caller does not know which class implements the method, so it cannot instantiate the right body. +- **In the implementer:** the class does not know which type arguments callers will use (other modules included), so it cannot fill a slot per instantiation ahead of time. + +## 3. Options + +**A. Erased slot.** The interface (or base-class) vtable gets one slot per generic method, holding an instantiation in which each type parameter is `any`. +- **At the call site:** box the arguments whose type is a type parameter, call through the slot, and unbox the result to the call's type argument. The unbox is checked, as `anyValue` is. +- **In the implementer:** the class provides the `any` instantiation of its own method for the slot. Direct calls on a known class keep the monomorphized fast path they use today. +- **Pros:** works across modules and with separately compiled implementers. +- **Cons:** boxing costs, and the body runs on `any`. A body that relies on the type parameter's real type (`sizeof()`, `new T()` through a constraint, arithmetic on `T extends number`) changes behaviour in the erased form. Such methods would have to be rejected for virtual dispatch with a clear error. + +**B. Closed-world instantiation table.** Collect every (method, type argument) pair called through an interface or base type in the program. Give each pair a slot, appended to every implementer's vtable. +- **Pros:** no boxing; the bodies run at their real types. +- **Cons:** needs whole-program knowledge. It breaks for `-shared` libraries and the JIT cache (modules compiled apart), and the slot layout changes as programs grow. Unfit for this compiler's cross-module model (`docs/interface-vtable-simplification-design.md`). + +**C. Dictionary passing.** Instantiate a generic method once, with a hidden argument that carries type information (size, descriptor, retain/release routines). This is what Swift does for unspecialized generics. +- **Pros:** no boxing of values; one body per method. +- **Cons:** a large change. Every generic body would need to lower against a runtime type description instead of concrete MLIR types, and the ownership passes (`-mm=own`, `-mm=rc`) reason about concrete types throughout. + +**D. Keep rejecting, but say so.** Report an error for a generic method overridden in a subclass, instead of silently calling the base method. Interfaces keep their current error. + +## 4. Recommendation + +1. **Now:** do D for classes. It turns a silent wrong call into an error. That's cheap, and correct regardless of what follows. +2. **Then:** A for interfaces and virtual class methods, limited to methods whose bodies the erased form can run unchanged: + - type parameters used only as values: stored, passed on, returned; + - no `sizeof`, no `new` through a constraint, no numeric operators on `T`. + + A method outside that set gets a clear error at its declaration. +3. **C** is the long-term general answer, but it is a project of its own. + +## 5. Work involved for A + +- **Interface declaration:** for each generic method, a slot whose function type has every type parameter replaced by `any` (`getInterfaceMethodNameAndType`, `InterfaceInfo::methods`). +- **Implementer:** when a class's vtable is built for the interface (`getVirtualTable`, `mlirGenObjectVirtualTableDefinitionForInterface`), instantiate the class method with `any` for each type parameter. Then put that symbol in the slot. +- **Call site:** `m.map(5)` through an interface or a base type becomes three steps: cast the arguments to `any`, make an indirect call through the slot, and cast the result to `number` (`castFromAny`, checked). +- **Base classes:** the class vtable gains the same erased slot for each generic method, and an override fills it. A call through a base-class reference uses it; a call on the exact class keeps today's direct instantiation. +- **Ownership under -mm=own:** a boxed argument is a fresh `any` the callee borrows. The result is unboxed into a value the caller owns. Both are existing patterns (spec 59, casts to `any`). +- **Tests:** + - an interface call with two type arguments; + - a subclass override reached through a base reference; + - a cross-module implementer (`-shared`); + - the rejection of a body that uses `sizeof`; + - each case under gc, rc, none and own. + +## 6. Non-goals + +- 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. diff --git a/tslang/docs/tuple-object-shape-ambiguity-design.md b/tslang/docs/tuple-object-shape-ambiguity-design.md index e012faf00..a51820896 100644 --- a/tslang/docs/tuple-object-shape-ambiguity-design.md +++ b/tslang/docs/tuple-object-shape-ambiguity-design.md @@ -1,6 +1,8 @@ # `isObjectShapedTuple` structural ambiguity: design -Status: **proposed, not implemented** — written for later review. Triggered by +Status: **proposed, not implemented** — written for later review. Re-checked 2026-10-29: still open, +`isObjectShapedTuple` (now `MLIRPrinter.h:288`) unchanged; the recommendation in §6 stands, and the first +step is the test §7 names, which pins the wrong output before any fix. Triggered by a code-review comment on `MLIRPrinter.h:232` during the cross-module class-extends work (`fix/cross-module-class-extends-crash` branch). A narrow symptom of the problem (numeric field ids) was already patched (see §4); this