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

via llvm-commits llvm-commits at lists.llvm.org
Sun Oct 5 03:28:03 PDT 2025


Author: Jakub Kuderski
Date: 2025-10-05T06:27:59-04:00
New Revision: f61789f5f6788322d8864f2c32021fd552f3f7b4

URL: https://github.com/llvm/llvm-project/commit/f61789f5f6788322d8864f2c32021fd552f3f7b4
DIFF: https://github.com/llvm/llvm-project/commit/f61789f5f6788322d8864f2c32021fd552f3f7b4.diff

LOG: [ADT] Add `DefaultUnreachable("msg")` to StringSwitch (#161976)

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.

Added: 
    

Modified: 
    llvm/include/llvm/ADT/StringSwitch.h
    llvm/unittests/ADT/StringSwitchTest.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/ADT/StringSwitch.h b/llvm/include/llvm/ADT/StringSwitch.h
index 86e591c71c92e..0ce7c57a358f2 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,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) {

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
+}


        


More information about the llvm-commits mailing list