Skip to content

Commit d9d4cc8

Browse files
committed
[ADT] Add DefaultUnreachable("msg") to StringSwitch
Similar to TypeSwitch (#161970), allow for explicit unreachable default case with a custom error message on unhandled cases. StringSwitch already allowed for checking if any of the cases matched with the conversion operator, but `DefaultUnreachable` is more explicit and allows for a custom message.
1 parent 85c7cea commit d9d4cc8

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

llvm/include/llvm/ADT/StringSwitch.h

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#define LLVM_ADT_STRINGSWITCH_H
1515

1616
#include "llvm/ADT/StringRef.h"
17+
#include "llvm/Support/ErrorHandling.h"
1718
#include <cassert>
1819
#include <cstring>
1920
#include <optional>
@@ -180,11 +181,15 @@ class StringSwitch {
180181
return Value;
181182
}
182183

183-
[[nodiscard]] operator R() {
184-
assert(Result && "Fell off the end of a string-switch");
185-
return std::move(*Result);
184+
[[nodiscard]] R DefaultUnreachable(
185+
const char *Message = "Fell off the end of a string-switch") {
186+
if (Result)
187+
return std::move(*Result);
188+
llvm_unreachable(Message);
186189
}
187190

191+
[[nodiscard]] operator R() { return DefaultUnreachable(); }
192+
188193
private:
189194
// Returns true when `Str` matches the `S` argument, and stores the result.
190195
bool CaseImpl(T &Value, StringLiteral S) {

llvm/unittests/ADT/StringSwitchTest.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,3 +230,19 @@ TEST(StringSwitchTest, CasesCopies) {
230230
"Foo", "Bar", "Baz", "Qux", Copyable{NumCopies});
231231
EXPECT_EQ(NumCopies, 1u);
232232
}
233+
234+
TEST(StringSwitchTest, DefaultUnreachable) {
235+
auto Translate = [](StringRef S) {
236+
return llvm::StringSwitch<int>(S)
237+
.Case("A", 0)
238+
.Case("B", 1)
239+
.DefaultUnreachable("Unhandled case");
240+
};
241+
242+
EXPECT_EQ(0, Translate("A"));
243+
EXPECT_EQ(1, Translate("B"));
244+
245+
#if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG)
246+
EXPECT_DEATH((void)Translate("C"), "Unhandled case");
247+
#endif
248+
}

0 commit comments

Comments
 (0)