[llvm] r305863 - Add a cantFail overload for Expected-reference (Expected<T&>) types.
Lang Hames via llvm-commits
llvm-commits at lists.llvm.org
Tue Jun 20 15:18:02 PDT 2017
Author: lhames
Date: Tue Jun 20 17:18:02 2017
New Revision: 305863
URL: http://llvm.org/viewvc/llvm-project?rev=305863&view=rev
Log:
Add a cantFail overload for Expected-reference (Expected<T&>) types.
Modified:
llvm/trunk/include/llvm/Support/Error.h
llvm/trunk/unittests/Support/ErrorTest.cpp
Modified: llvm/trunk/include/llvm/Support/Error.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/Error.h?rev=305863&r1=305862&r2=305863&view=diff
==============================================================================
--- llvm/trunk/include/llvm/Support/Error.h (original)
+++ llvm/trunk/include/llvm/Support/Error.h Tue Jun 20 17:18:02 2017
@@ -1076,6 +1076,27 @@ T cantFail(Expected<T> ValOrErr) {
llvm_unreachable("Failure value returned from cantFail wrapped call");
}
+/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
+/// returns the contained reference.
+///
+/// This function can be used to wrap calls to fallible functions ONLY when it
+/// is known that the Error will always be a success value. E.g.
+///
+/// @code{.cpp}
+/// // foo only attempts the fallible operation if DoFallibleOperation is
+/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
+/// Expected<Bar&> foo(bool DoFallibleOperation);
+///
+/// Bar &X = cantFail(foo(false));
+/// @endcode
+template <typename T>
+T& cantFail(Expected<T&> ValOrErr) {
+ if (ValOrErr)
+ return *ValOrErr;
+ else
+ llvm_unreachable("Failure value returned from cantFail wrapped call");
+}
+
} // end namespace llvm
#endif // LLVM_SUPPORT_ERROR_H
Modified: llvm/trunk/unittests/Support/ErrorTest.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/unittests/Support/ErrorTest.cpp?rev=305863&r1=305862&r2=305863&view=diff
==============================================================================
--- llvm/trunk/unittests/Support/ErrorTest.cpp (original)
+++ llvm/trunk/unittests/Support/ErrorTest.cpp Tue Jun 20 17:18:02 2017
@@ -475,6 +475,10 @@ TEST(Error, CantFailSuccess) {
int X = cantFail(Expected<int>(42));
EXPECT_EQ(X, 42) << "Expected value modified by cantFail";
+
+ int Dummy = 42;
+ int &Y = cantFail(Expected<int&>(Dummy));
+ EXPECT_EQ(&Dummy, &Y) << "Reference mangled by cantFail";
}
// Test that cantFail results in a crash if you pass it a failure value.
More information about the llvm-commits
mailing list