From 16d0f5a96b84197458307fec1bb3e4fb31efe59d Mon Sep 17 00:00:00 2001 From: Lang Hames Date: Tue, 20 Jun 2017 22:18:02 +0000 Subject: [PATCH] Add a cantFail overload for Expected-reference (Expected) types. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@305863 91177308-0d34-0410-b5e6-96231b3b80d8 --- include/llvm/Support/Error.h | 21 +++++++++++++++++++++ unittests/Support/ErrorTest.cpp | 4 ++++ 2 files changed, 25 insertions(+) diff --git a/include/llvm/Support/Error.h b/include/llvm/Support/Error.h index 1e27e0b821f..9a7fa0ae635 100644 --- a/include/llvm/Support/Error.h +++ b/include/llvm/Support/Error.h @@ -1076,6 +1076,27 @@ T cantFail(Expected 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 foo(bool DoFallibleOperation); +/// +/// Bar &X = cantFail(foo(false)); +/// @endcode +template +T& cantFail(Expected ValOrErr) { + if (ValOrErr) + return *ValOrErr; + else + llvm_unreachable("Failure value returned from cantFail wrapped call"); +} + } // end namespace llvm #endif // LLVM_SUPPORT_ERROR_H diff --git a/unittests/Support/ErrorTest.cpp b/unittests/Support/ErrorTest.cpp index 382346cd231..299fc50b469 100644 --- a/unittests/Support/ErrorTest.cpp +++ b/unittests/Support/ErrorTest.cpp @@ -475,6 +475,10 @@ TEST(Error, CantFailSuccess) { int X = cantFail(Expected(42)); EXPECT_EQ(X, 42) << "Expected value modified by cantFail"; + + int Dummy = 42; + int &Y = cantFail(Expected(Dummy)); + EXPECT_EQ(&Dummy, &Y) << "Reference mangled by cantFail"; } // Test that cantFail results in a crash if you pass it a failure value. -- 2.40.0