Skip to content

Commit f61789f

Browse files
authored
[ADT] Add DefaultUnreachable("msg") to StringSwitch (llvm#161976)
Similar to TypeSwitch (llvm#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 90d5795 commit f61789f

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

llvm/include/llvm/ADT/StringSwitch.h

Lines changed: 9 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,16 @@ 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+
/// Declare default as unreachable, making sure that all cases were handled.
185+
[[nodiscard]] R DefaultUnreachable(
186+
const char *Message = "Fell off the end of a string-switch") {
187+
if (Result)
188+
return std::move(*Result);
189+
llvm_unreachable(Message);
186190
}
187191

192+
[[nodiscard]] operator R() { return DefaultUnreachable(); }
193+
188194
private:
189195
// Returns true when `Str` matches the `S` argument, and stores the result.
190196
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)