[PATCH] D140265: [llvm][ADT] Allow returning `std::nullopt` in TypeSwitch
Markus Böck via Phabricator via llvm-commits
llvm-commits at lists.llvm.org
Sat Dec 17 15:02:05 PST 2022
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1d43966bc33a: [llvm][ADT] Allow returning `std::nullopt` in TypeSwitch (authored by zero9178).
Repository:
rG LLVM Github Monorepo
CHANGES SINCE LAST ACTION
https://reviews.llvm.org/D140265/new/
https://reviews.llvm.org/D140265
Files:
llvm/include/llvm/ADT/TypeSwitch.h
llvm/unittests/ADT/TypeSwitchTest.cpp
Index: llvm/unittests/ADT/TypeSwitchTest.cpp
===================================================================
--- llvm/unittests/ADT/TypeSwitchTest.cpp
+++ llvm/unittests/ADT/TypeSwitchTest.cpp
@@ -86,3 +86,31 @@
EXPECT_EQ(0, translate(DerivedD()));
EXPECT_EQ(-1, translate(DerivedE()));
}
+
+TEST(TypeSwitchTest, CaseOptional) {
+ auto translate = [](auto value) {
+ return TypeSwitch<Base *, std::optional<int>>(&value)
+ .Case([](DerivedA *) { return 0; })
+ .Case([](DerivedC *) { return std::nullopt; })
+ .Default([](Base *) { return -1; });
+ };
+ EXPECT_EQ(0, translate(DerivedA()));
+ EXPECT_EQ(std::nullopt, translate(DerivedC()));
+ EXPECT_EQ(-1, translate(DerivedD()));
+ EXPECT_EQ(std::nullopt,
+ (TypeSwitch<Base *, std::optional<int>>(nullptr).Default(
+ [](Base *) { return std::nullopt; })));
+}
+
+TEST(TypeSwitchTest, CasesOptional) {
+ auto translate = [](auto value) {
+ return TypeSwitch<Base *, std::optional<int>>(&value)
+ .Case<DerivedB, DerivedC>([](auto *) { return std::nullopt; })
+ .Case([](DerivedA *) { return 0; })
+ .Default([](Base *) { return -1; });
+ };
+ EXPECT_EQ(0, translate(DerivedA()));
+ EXPECT_EQ(std::nullopt, translate(DerivedB()));
+ EXPECT_EQ(std::nullopt, translate(DerivedC()));
+ EXPECT_EQ(-1, translate(DerivedD()));
+}
Index: llvm/include/llvm/ADT/TypeSwitch.h
===================================================================
--- llvm/include/llvm/ADT/TypeSwitch.h
+++ llvm/include/llvm/ADT/TypeSwitch.h
@@ -119,7 +119,7 @@
// Check to see if CaseT applies to 'value'.
if (auto caseValue = BaseT::template castValue<CaseT>(this->value))
- result = caseFn(caseValue);
+ result.emplace(caseFn(caseValue));
return *this;
}
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D140265.483780.patch
Type: text/x-patch
Size: 1807 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20221217/e0155a81/attachment.bin>
More information about the llvm-commits
mailing list