[llvm] [ADT] Add `DefaultUnreachable("msg")` to StringSwitch (PR #161976)

via llvm-commits llvm-commits at lists.llvm.org
Sat Oct 4 14:08:27 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-adt

Author: Jakub Kuderski (kuhar)

<details>
<summary>Changes</summary>

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.

---
Full diff: https://github.com/llvm/llvm-project/pull/161976.diff


2 Files Affected:

- (modified) llvm/include/llvm/ADT/StringSwitch.h (+8-3) 
- (modified) llvm/unittests/ADT/StringSwitchTest.cpp (+16) 


``````````diff
diff --git a/llvm/include/llvm/ADT/StringSwitch.h b/llvm/include/llvm/ADT/StringSwitch.h
index 86e591c71c92e..18eadcd10fb9b 100644
--- a/llvm/include/llvm/ADT/StringSwitch.h
+++ b/llvm/include/llvm/ADT/StringSwitch.h
@@ -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>
@@ -180,11 +181,15 @@ class StringSwitch {
     return Value;
   }
 
-  [[nodiscard]] operator R() {
-    assert(Result && "Fell off the end of a string-switch");
-    return std::move(*Result);
+  [[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) {
diff --git a/llvm/unittests/ADT/StringSwitchTest.cpp b/llvm/unittests/ADT/StringSwitchTest.cpp
index 2953f4b0a381b..bcb1521baa287 100644
--- a/llvm/unittests/ADT/StringSwitchTest.cpp
+++ b/llvm/unittests/ADT/StringSwitchTest.cpp
@@ -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
+}

``````````

</details>


https://github.com/llvm/llvm-project/pull/161976


More information about the llvm-commits mailing list