From c7a6be20c6638b25aa7dd710faeefa859119ed47 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 14:52:29 +0000 Subject: [PATCH] `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."); +}