Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 161 additions & 0 deletions tslang/lib/TypeScript/MLIRGenCast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<Holder><any>runner`), was called through garbage.
if (isa<mlir_ts::AnyType>(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.
Expand Down Expand Up @@ -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))
{
Expand Down Expand Up @@ -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<ClassInfo::TypePtr> implementers;
SmallVector<ClassInfo::TypePtr> others;
llvm::SmallPtrSet<ClassInfo *, 16> seenClasses;
llvm::SmallPtrSet<NamespaceInfo *, 16> seenNamespaces;
std::function<void(NamespaceInfo::TypePtr)> 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<T>(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 = <TYPE_ANY_INTERFACE_ALIAS>b;\n");
for (auto [index, _] : enumerate(implementers))
{
ss << S("if (i instanceof TYPE_INST_ALIAS") << index << S(") return <TYPE_INST_ALIAS") << index << S(">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 <T><TYPE_ANY_INTERFACE_ALIAS>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<mlir::Value, 4> operands;
operands.push_back(value);

NodeFactory nf(NodeFactoryFlags::None);
return mlirGenCallExpression(
location,
funcResult,
{
nf.createTypeReferenceNode(nf.createIdentifier(S(".TYPE_ALIAS_T")).as<Node>()),
},
operands,
funcCallGenContext);
}

ValueOrLogicalResult MLIRGenImpl::castFromUnion(mlir::Location location, mlir::Type type, mlir::Value value, const GenContext &genContext)
{
if (auto unionType = dyn_cast<mlir_ts::UnionType>(value.getType()))
Expand Down
7 changes: 7 additions & 0 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -16116,6 +16119,10 @@ class MLIRGenImpl

llvm::ScopedHashTable<StringRef, ClassInfo::TypePtr> 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<mlir::Type> cppVTableHiddenReturns;
// those of them whose hidden pointer goes before `this` (the Itanium ABI)
Expand Down
5 changes: 5 additions & 0 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down
100 changes: 100 additions & 0 deletions tslang/test/tester/tests/00any_to_interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// An `any` holds the kind of what it holds, not which interface an interface value was made for.
// `<Holder><any>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 = <Holder><any>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 = <Holder><any>new Walker(show);
h.f(new Item(1000));
} catch (e) {
caught = true;
}

assert(caught, "a Walker is no Holder");
}

function implementer() {
const h1 = <Holder><any>new Keeper(show);
h1.f(new Item(1));

const kh: Holder = new Keeper(show);
const h2 = <Holder><any>kh;
h2.f(new Item(2));
}

function castBeforeTheVTable() {
const h = <Holder><any>new Later(show);
h.f(new Item(4));
}

function roundTrip() {
const r: Runner = new Walker(show);
const back = <Runner><any>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.");
}
Loading