From c4a6679719bf3763053233f9fee023fbe68a4ef6 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 28 Oct 2026 09:48:36 +0000 Subject: [PATCH] Cast from any to an interface asks the object what class it is `runner` compiled to a plain unbox: the box's payload was read as Holder's (this, vtable) pair, so a Runner value (Runner's vtable) or a class object in the box was called through garbage - an access violation in every memory model. An `any` records only the kind of what it holds, not which interface an interface value was made for, so there is no run-time lookup by interface name. castAnyToInterface generates `___unbox_interface`, which asks the object behind the box (`instanceof`): - a class with a vtable for I - it declares `implements I`, or some cast in the module makes one (classInterfaceVTablesCast, recorded from the discovery pass on, so a cast later in the module counts) - gives I through that vtable, from a class object or an interface value; - any other class of this module throws "class 'X' does not implement interface 'I'"; no vtable is made for it here, so no new way to reach a class's fields appears; - anything else (an interface value over an object literal or another module's class, a number used as a token) is read as before, so a value boxed as the interface it is cast to round-trips. Test: 00any_to_interface (gc, rc, none, own; compile and JIT). Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenCast.cpp | 161 ++++++++++++++++++ tslang/lib/TypeScript/MLIRGenImpl.h | 7 + tslang/test/tester/CMakeLists.txt | 5 + .../test/tester/tests/00any_to_interface.ts | 100 +++++++++++ 4 files changed, 273 insertions(+) create mode 100644 tslang/test/tester/tests/00any_to_interface.ts diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index a830e953e..5d4076e1b 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -1166,6 +1166,17 @@ namespace mlirgen return castInterfaceToInterface(location, value, srcInterfaceType, interfaceType, genContext); } + // An `any` holds no interface's name, only its kind: what it holds was read as the + // interface's (this, vtable) pair, and a class object, or an interface value made for + // another interface (`runner`), was called through garbage. + if (isa(valueType) && !genContext.allowPartialResolve) + { + if (auto interfaceInfo = getInterfaceInfoByFullName(interfaceType.getName().getValue())) + { + return castAnyToInterface(location, interfaceType, interfaceInfo, value, genContext); + } + } + // `J | null` or `C | null` (a `J | undefined` given to `I | undefined` gets here too) is stored // as its one member, null a null pointer in it: this is the cast of that member. A plain cast // kept J's vtable for I, and lowering could not make a class pointer an interface. @@ -1225,6 +1236,9 @@ namespace mlirgen auto interfaceInfo = getInterfaceInfoByFullName(interfaceType.getName().getValue()); assert(interfaceInfo); + // known from the discovery pass on, wherever in the module the cast is (castAnyToInterface) + classInterfaceVTablesCast.insert(interfaceVTableNameForClass(classInfo, interfaceInfo)); + if (auto createdInterfaceVTableForClass = mlirGenCreateInterfaceVTableForClass(location, classInfo, interfaceInfo, genContext)) { @@ -2548,6 +2562,153 @@ namespace mlirgen funcCallGenContext); } + // `any` to an interface. The box knows the kind of what it holds, not which interface an interface + // value was made for, so the object behind it is asked what class it is (`instanceof`): + // - a class with a vtable for the interface - it declares it, or a cast somewhere in the module + // makes one (classInterfaceVTablesCast, filled from the discovery pass on, so a cast later in + // the module counts) - gives the interface through that vtable, from a class object or an + // interface value alike; + // - any other class of this module can't: no vtable for the interface was made for it, and none + // is made here (one made here would be a way to the class's fields that nothing else in the + // module shows), so the cast throws. A class object no class answers for throws too; + // - anything else - an interface value over an object literal or a class of another module, a + // number used as a token - is read as the interface's pair, as before: an `any` holding the + // interface it is cast to round-trips. + ValueOrLogicalResult MLIRGenImpl::castAnyToInterface(mlir::Location location, mlir_ts::InterfaceType interfaceType, + InterfaceInfo::TypePtr interfaceInfo, mlir::Value value, + const GenContext &genContext) + { + SmallVector implementers; + SmallVector others; + llvm::SmallPtrSet seenClasses; + llvm::SmallPtrSet seenNamespaces; + std::function collectClasses = [&](NamespaceInfo::TypePtr namespaceInfo) { + if (!seenNamespaces.insert(namespaceInfo.get()).second) + { + return; + } + + for (auto &classEntry : namespaceInfo->classesMap) + { + auto classInfo = classEntry.getValue(); + // `instanceof` asks the class's `.instanceOf`, which a @value or @cpp class has none of + if (!classInfo || !classInfo->classType || !classInfo->hasRTTI || classInfo->isValue + || classInfo->isCppVTable || !seenClasses.insert(classInfo.get()).second) + { + continue; + } + + if (classInfo->getImplementIndex(interfaceInfo->fullName) >= 0 + || classInterfaceVTablesCast.contains(interfaceVTableNameForClass(classInfo, interfaceInfo))) + { + implementers.push_back(classInfo); + } + else if (!classInfo->isDeclaration) + { + others.push_back(classInfo); + } + } + + for (auto &namespaceEntry : namespaceInfo->namespacesMap) + { + collectClasses(namespaceEntry.getValue()); + } + }; + + collectClasses(rootNamespace); + + // info, we add "_" extra as scanner append "_" in front of "__"; + auto funcName = "___unbox_interface"; + + // the classes asked differ from one interface to another + removeGenericFunctionMap(funcName); + + auto throwNotImplemented = [&](stringstream &ss, StringRef className) { + ss << S("throw \"Can't cast from any: class '") << stows(className.str()) + << S("' does not implement interface '") << stows(interfaceInfo->fullName.str()) << S("'\";\n"); + }; + + // `a` narrowed by `typeof` is the first word of the box; `b` is the box + stringstream ss; + ss << S("function __unbox_interface(a: any) : T {\nconst b = a;\n"); + ss << S("if (typeof a == 'class') {\n"); + for (auto [index, _] : enumerate(implementers)) + { + ss << S("if (a instanceof TYPE_INST_ALIAS") << index << S(") return a;\n"); + } + + for (auto [index, other] : enumerate(others)) + { + ss << S("if (a instanceof TYPE_OTHER_ALIAS") << index << S(") "); + throwNotImplemented(ss, other->fullName); + } + + ss << S("throw \"Can't cast from any: the class object has no vtable for interface '") + << stows(interfaceInfo->fullName.str()) << S("'\";\n}\n"); + + ss << S("if (typeof a == 'interface') {\nconst i = b;\n"); + for (auto [index, _] : enumerate(implementers)) + { + ss << S("if (i instanceof TYPE_INST_ALIAS") << index << S(") return i;\n"); + } + + for (auto [index, other] : enumerate(others)) + { + ss << S("if (i instanceof TYPE_OTHER_ALIAS") << index << S(") "); + throwNotImplemented(ss, other->fullName); + } + + ss << S("}\n"); + ss << S("return a;\n}\n"); + + auto src = ss.str(); + + // see castPrimitiveTypeFromAny: the call site is the location until the call below instantiates + // the function + MLIRLocationGuard vgLoc(overwriteLoc); + overwriteLoc = location; + + if (mlir::failed(parsePartialStatements(src))) + { + assert(false); + return mlir::failure(); + } + + auto funcResult = resolveIdentifier(location, funcName, genContext); + + assert(funcResult); + + GenContext funcCallGenContext(genContext); + funcCallGenContext.typeAliasMap.insert({".TYPE_ALIAS_T", interfaceType}); + for (auto [index, classInfo] : enumerate(implementers)) + { + funcCallGenContext.typeAliasMap.insert({"TYPE_INST_ALIAS" + std::to_string(index), classInfo->classType}); + } + + for (auto [index, classInfo] : enumerate(others)) + { + funcCallGenContext.typeAliasMap.insert({"TYPE_OTHER_ALIAS" + std::to_string(index), classInfo->classType}); + } + + // see castPrimitiveTypeFromAny: any interface type reads an interface value out of the box + funcCallGenContext.typeAliasMap.insert( + {"TYPE_ANY_INTERFACE_ALIAS", + mlir_ts::InterfaceType::get(builder.getContext(), mlir::FlatSymbolRefAttr::get(builder.getContext(), ".any_interface"))}); + + SmallVector operands; + operands.push_back(value); + + NodeFactory nf(NodeFactoryFlags::None); + return mlirGenCallExpression( + location, + funcResult, + { + nf.createTypeReferenceNode(nf.createIdentifier(S(".TYPE_ALIAS_T")).as()), + }, + operands, + funcCallGenContext); + } + ValueOrLogicalResult MLIRGenImpl::castFromUnion(mlir::Location location, mlir::Type type, mlir::Value value, const GenContext &genContext) { if (auto unionType = dyn_cast(value.getType())) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 7a0df99a9..39f80290a 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -14265,6 +14265,9 @@ class MLIRGenImpl bool areIncompatibleUnrelatedClasses(mlir::Location location, mlir::Type type, mlir::Type valueType, std::string &mismatch); ValueOrLogicalResult castPrimitiveTypeFromAny(mlir::Location location, mlir::Type type, mlir::Value value, const GenContext &genContext); + ValueOrLogicalResult castAnyToInterface(mlir::Location location, mlir_ts::InterfaceType interfaceType, + InterfaceInfo::TypePtr interfaceInfo, mlir::Value value, + const GenContext &genContext); // TODO: remove using typeof for Union types as it can't handle types such as 2 tuples in union etc ValueOrLogicalResult castFromUnion(mlir::Location location, mlir::Type type, mlir::Value value, const GenContext &genContext); @@ -16116,6 +16119,10 @@ class MLIRGenImpl llvm::ScopedHashTable fullNameClassesMap; + // the vtables of classes for interfaces they don't declare that casts ask for + // (interfaceVTableNameForClass), from the discovery pass on: see castAnyToInterface + llvm::StringSet<> classInterfaceVTablesCast; + // the @cpp methods returning a C++ record (by function name): the record's type llvm::StringMap cppVTableHiddenReturns; // those of them whose hidden pointer goes before `this` (the Itanium ABI) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index bc9fbdc81..4d744ca0c 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -685,6 +685,8 @@ tslang_add_test(NAME test-compile-00-interface-indexer COMMAND test-runner "${PR tslang_add_test(NAME test-compile-00-class-or-interface-to-tuple COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_or_interface_to_tuple.ts") tslang_add_test(NAME test-compile-00-any COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00any.ts") tslang_add_test(NAME test-compile-00-any-unbox-interface-class COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_unbox_interface_class.ts") +tslang_add_test(NAME test-compile-00-any-to-interface COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_to_interface.ts") +tslang_add_test(NAME test-compile-own-00-any-to-interface COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_to_interface.ts") tslang_add_test(NAME test-compile-00-interface-instanceof COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_instanceof.ts") tslang_add_test(NAME test-compile-01-any COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/01any.ts") tslang_add_test(NAME test-compile-00-any-types COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_types.ts") @@ -1291,6 +1293,8 @@ tslang_add_test(NAME test-jit-00-interface-indexer COMMAND test-runner -jit "${P tslang_add_test(NAME test-jit-00-class-or-interface-to-tuple COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_or_interface_to_tuple.ts") tslang_add_test(NAME test-jit-00-any COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00any.ts") tslang_add_test(NAME test-jit-00-any-unbox-interface-class COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_unbox_interface_class.ts") +tslang_add_test(NAME test-jit-00-any-to-interface COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_to_interface.ts") +tslang_add_test(NAME test-jit-own-00-any-to-interface COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_to_interface.ts") tslang_add_test(NAME test-jit-00-interface-instanceof COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_instanceof.ts") tslang_add_test(NAME test-jit-01-any COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/01any.ts") tslang_add_test(NAME test-jit-00-any-types COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_types.ts") @@ -2040,6 +2044,7 @@ set(TSLANG_CORPUS 00any_compare.ts 00any_generic_equals.ts 00any_types.ts + 00any_to_interface.ts 00any.ts 00any_equality_undefined.ts 00array_assignment5.ts diff --git a/tslang/test/tester/tests/00any_to_interface.ts b/tslang/test/tester/tests/00any_to_interface.ts new file mode 100644 index 000000000..b29b3dd4a --- /dev/null +++ b/tslang/test/tester/tests/00any_to_interface.ts @@ -0,0 +1,100 @@ +// An `any` holds the kind of what it holds, not which interface an interface value was made for. +// `runner` read the Runner value's vtable as Holder's and called garbage; a class object +// in the box was read as an interface's (this, vtable) pair. The object is now asked what class it +// is: a class with a vtable for the interface gives it, any other class of the module throws, and +// anything else is read as before, so a value boxed as the interface it is cast to round-trips. + +class Item { + constructor(public n: number) {} +} + +interface Runner { + walk(a: Item[]): number; +} + +interface Holder { + f: (v: Item) => void; +} + +// a Runner, and no Holder anywhere in the module +class Walker implements Runner { + constructor(public f: (v: Item) => void) {} + walk(a: Item[]): number { + return 1; + } +} + +class Keeper implements Holder { + constructor(public f: (v: Item) => void) {} +} + +// a Holder through a cast made only further down the module (sawLater) +class Later { + constructor(public f: (v: Item) => void) {} +} + +let shown: number = 0; +function show(v: Item) { + shown += v.n; +} + +function otherInterface() { + let caught = false; + try { + const r: Runner = new Walker(show); + const h = r; + h.f(new Item(1000)); + } catch (e) { + caught = true; + } + + assert(caught, "a Runner over a Walker is no Holder"); +} + +function classObject() { + let caught = false; + try { + const h = new Walker(show); + h.f(new Item(1000)); + } catch (e) { + caught = true; + } + + assert(caught, "a Walker is no Holder"); +} + +function implementer() { + const h1 = new Keeper(show); + h1.f(new Item(1)); + + const kh: Holder = new Keeper(show); + const h2 = kh; + h2.f(new Item(2)); +} + +function castBeforeTheVTable() { + const h = new Later(show); + h.f(new Item(4)); +} + +function roundTrip() { + const r: Runner = new Walker(show); + const back = r; + assert(back.walk([]) == 1, "round trip"); +} + +function sawLater() { + const h: Holder = new Later(show); + h.f(new Item(8)); +} + +function main() { + otherInterface(); + classObject(); + implementer(); + castBeforeTheVTable(); + roundTrip(); + sawLater(); + assert(shown == 15, "every Holder reached show"); + print("done."); +}