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
3 changes: 2 additions & 1 deletion tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
22 changes: 15 additions & 7 deletions tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::TupleType, mlir_ts::ConstTupleType>(type))
std::string text;
llvm::raw_string_ostream os(text);
if (auto interfaceType = dyn_cast<mlir_ts::InterfaceType>(type))
{
os << "interface " << interfaceType.getName().getValue();
}
else if (isa<mlir_ts::TupleType, mlir_ts::ConstTupleType>(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;
}
Expand Down
12 changes: 12 additions & 0 deletions tslang/include/TypeScript/TypeScriptOps.td
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [{
Expand Down
2 changes: 1 addition & 1 deletion tslang/lib/TypeScript/LowerToAffineLoops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
23 changes: 22 additions & 1 deletion tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7852,6 +7852,27 @@ struct IsTupleOfLayoutOpLowering : public TsLlvmPattern<mlir_ts::IsTupleOfLayout
}
};

struct IsTypeTagOfOpLowering : public TsLlvmPattern<mlir_ts::IsTypeTagOfOp>
{
using TsLlvmPattern<mlir_ts::IsTypeTagOfOp>::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<LLVM::ConstantOp>(
loc, th.getI32Type(), rewriter.getI32IntegerAttr((int32_t)TypeOfOpHelper::layoutIdOf(op.getType())));
rewriter.replaceOpWithNewOp<LLVM::ICmpOp>(op, LLVM::ICmpPredicate::eq, layout, expected);
return success();
}
};

struct TypeOfAnyOpLowering : public TsLlvmPattern<mlir_ts::TypeOfAnyOp>
{
using TsLlvmPattern<mlir_ts::TypeOfAnyOp>::TsLlvmPattern;
Expand Down Expand Up @@ -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,
Expand Down
105 changes: 102 additions & 3 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::UnionType>(evaluate(binExpr->right, genContext)))
{
auto key = builder.getStringAttr(convertWideToUTF8(binExpr->left.as<LiteralLikeNode>()->text));
SmallVector<mlir::Type> 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;
Expand Down Expand Up @@ -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<mlir::Type> &withKey)
{
mlir::Type baseType;
if (!isa_and_nonnull<mlir::StringAttr>(key) || !mth.isUnionTypeNeedsTag(location, unionType, baseType))
{
return false;
}

for (auto member : unionType.getTypes())
{
auto interfaceType = dyn_cast<mlir_ts::InterfaceType>(member);
if (!interfaceType)
{
return false;
}

auto interfaceInfo = getInterfaceInfoByFullName(interfaceType.getName().getValue());
if (!interfaceInfo)
{
return false;
}

auto name = mlir::cast<mlir::StringAttr>(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<mlir::Type> members)
{
auto tag = builder.create<mlir_ts::GetTypeInfoFromUnionOp>(location, getStringType(), unionValue);
mlir::Value holds;
for (auto member : members)
{
mlir::Value isMember = builder.create<mlir_ts::IsTypeTagOfOp>(location, getBooleanType(), tag, mlir::TypeAttr::get(member));
holds = holds ? builder.create<mlir_ts::LogicalBinaryOp>(
location, getBooleanType(), builder.getI32IntegerAttr((int)SyntaxKind::BarBarToken), holds, isMember)
: isMember;
}

return holds;
}

ValueOrLogicalResult mlirGenInLogic(BinaryExpression binaryExpressionAST, const GenContext &genContext)
{
// Supports only array now
Expand Down Expand Up @@ -6070,10 +6140,24 @@ class MLIRGenImpl
return mlir::failure();
}

if (isa<mlir_ts::UnionType>(rightExpressionValue.getType()))
if (auto unionType = dyn_cast<mlir_ts::UnionType>(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<mlir_ts::ConstantOp>();
SmallVector<mlir::Type> 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<mlir_ts::ConstantOp>())
Expand Down Expand Up @@ -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<mlir_ts::UnionType>(resultLeftfType); unionType && isa<mlir_ts::InterfaceType>(rightType))
{
mlir::Type baseType;
if (llvm::is_contained(unionType.getTypes(), rightType) && mth.isUnionTypeNeedsTag(location, unionType, baseType))
{
auto refType = dyn_cast<mlir_ts::RefType>(resultLeftValue.getType());
auto leftValue = refType
? builder.create<mlir_ts::LoadOp>(location, refType.getElementType(), resultLeftValue).getResult()
: resultLeftValue;
return mlirGenUnionHoldsOneOf(location, leftValue, {rightType});
}
}

LLVM_DEBUG(llvm::dbgs() << "!! instanceOf precalc value: " << (resultLeftfType == rightType) << " '" << resultLeftfType
<< "' is '" << rightType << "'\n";);

Expand Down
2 changes: 1 addition & 1 deletion tslang/lib/TypeScript/OwnershipInferenceMoves.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::HasValueOp, mlir_ts::GetTypeInfoFromUnionOp, mlir_ts::TypeOfOp,
mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp>(user))
mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp, mlir_ts::IsTypeTagOfOp>(user))
{
return true;
}
Expand Down
3 changes: 3 additions & 0 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down
83 changes: 83 additions & 0 deletions tslang/test/tester/tests/00in_interface_union.ts
Original file line number Diff line number Diff line change
@@ -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.");
}
Loading