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
12 changes: 9 additions & 3 deletions llvm/include/llvm/ADT/StringSwitch.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#define LLVM_ADT_STRINGSWITCH_H

#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
#include <cstring>
#include <optional>
Expand Down Expand Up @@ -180,11 +181,16 @@ class StringSwitch {
return Value;
}

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

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

private:
// Returns true when `Str` matches the `S` argument, and stores the result.
bool CaseImpl(T &Value, StringLiteral S) {
Expand Down
16 changes: 16 additions & 0 deletions llvm/unittests/ADT/StringSwitchTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -230,3 +230,19 @@ TEST(StringSwitchTest, CasesCopies) {
"Foo", "Bar", "Baz", "Qux", Copyable{NumCopies});
EXPECT_EQ(NumCopies, 1u);
}

TEST(StringSwitchTest, DefaultUnreachable) {
auto Translate = [](StringRef S) {
return llvm::StringSwitch<int>(S)
.Case("A", 0)
.Case("B", 1)
.DefaultUnreachable("Unhandled case");
};

EXPECT_EQ(0, Translate("A"));
EXPECT_EQ(1, Translate("B"));

#if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG)
EXPECT_DEATH((void)Translate("C"), "Unhandled case");
#endif
}