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
19 changes: 16 additions & 3 deletions llvm/include/llvm/ADT/TypeSwitch.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include <optional>

namespace llvm {
Expand Down Expand Up @@ -117,11 +118,16 @@ class TypeSwitch : public detail::TypeSwitchBase<TypeSwitch<T, ResultT>, T> {
return defaultResult;
}

[[nodiscard]] operator ResultT() {
assert(result && "Fell off the end of a type-switch");
return std::move(*result);
/// Declare default as unreachable, making sure that all cases were handled.
[[nodiscard]] ResultT DefaultUnreachable(
const char *message = "Fell off the end of a type-switch") {
if (result)
return std::move(*result);
llvm_unreachable(message);
}

[[nodiscard]] operator ResultT() { return DefaultUnreachable(); }

private:
/// The pointer to the result of this switch statement, once known,
/// null before that.
Expand Down Expand Up @@ -158,6 +164,13 @@ class TypeSwitch<T, void>
defaultFn(this->value);
}

/// Declare default as unreachable, making sure that all cases were handled.
void DefaultUnreachable(
const char *message = "Fell off the end of a type-switch") {
if (!foundMatch)
llvm_unreachable(message);
}

private:
/// A flag detailing if we have already found a match.
bool foundMatch = false;
Expand Down
28 changes: 28 additions & 0 deletions llvm/unittests/ADT/TypeSwitchTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,31 @@ TEST(TypeSwitchTest, CasesOptional) {
EXPECT_EQ(std::nullopt, translate(DerivedC()));
EXPECT_EQ(-1, translate(DerivedD()));
}

TEST(TypeSwitchTest, DefaultUnreachableWithValue) {
auto translate = [](auto value) {
return TypeSwitch<Base *, int>(&value)
.Case([](DerivedA *) { return 0; })
.DefaultUnreachable("Unhandled type");
};
EXPECT_EQ(0, translate(DerivedA()));

#if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG)
EXPECT_DEATH((void)translate(DerivedD()), "Unhandled type");
#endif
}

TEST(TypeSwitchTest, DefaultUnreachableWithVoid) {
auto translate = [](auto value) {
int result = -1;
TypeSwitch<Base *>(&value)
.Case([&result](DerivedA *) { result = 0; })
.DefaultUnreachable("Unhandled type");
return result;
};
EXPECT_EQ(0, translate(DerivedA()));

#if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG)
EXPECT_DEATH((void)translate(DerivedD()), "Unhandled type");
#endif
}