1 //===- llvm/Support/ErrorOr.h - Error Smart Pointer -----------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 /// Provides ErrorOr<T> smart pointer.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_SUPPORT_ERROR_OR_H
17 #define LLVM_SUPPORT_ERROR_OR_H
19 #include "llvm/ADT/PointerIntPair.h"
20 #include "llvm/Support/AlignOf.h"
21 #include "llvm/Support/system_error.h"
22 #include "llvm/Support/type_traits.h"
25 #if LLVM_HAS_CXX11_TYPETRAITS
26 #include <type_traits>
30 struct ErrorHolderBase {
35 ErrorHolderBase() : RefCount(1) {}
47 virtual ~ErrorHolderBase() {}
51 struct ErrorHolder : ErrorHolderBase {
52 #if LLVM_HAS_RVALUE_REFERENCES
53 ErrorHolder(T &&UD) : UserData(llvm_move(UD)) {}
55 ErrorHolder(T &UD) : UserData(UD) {}
60 template<class Tp> struct ErrorOrUserDataTraits : llvm::false_type {};
62 #if LLVM_HAS_CXX11_TYPETRAITS && LLVM_HAS_RVALUE_REFERENCES
63 template<class T, class V>
64 typename std::enable_if< std::is_constructible<T, V>::value
65 , typename std::remove_reference<V>::type>::type &&
66 moveIfMoveConstructible(V &Val) {
67 return std::move(Val);
70 template<class T, class V>
71 typename std::enable_if< !std::is_constructible<T, V>::value
72 , typename std::remove_reference<V>::type>::type &
73 moveIfMoveConstructible(V &Val) {
77 template<class T, class V>
78 V &moveIfMoveConstructible(V &Val) {
83 /// \brief Stores a reference that can be changed.
85 class ReferenceStorage {
89 ReferenceStorage(T &Ref) : Storage(&Ref) {}
91 operator T &() const { return *Storage; }
92 T &get() const { return *Storage; }
95 /// \brief Represents either an error or a value T.
97 /// ErrorOr<T> is a pointer-like class that represents the result of an
98 /// operation. The result is either an error, or a value of type T. This is
99 /// designed to emulate the usage of returning a pointer where nullptr indicates
100 /// failure. However instead of just knowing that the operation failed, we also
101 /// have an error_code and optional user data that describes why it failed.
103 /// It is used like the following.
105 /// ErrorOr<Buffer> getBuffer();
106 /// void handleError(error_code ec);
108 /// auto buffer = getBuffer();
110 /// handleError(buffer);
111 /// buffer->write("adena");
114 /// ErrorOr<T> also supports user defined data for specific error_codes. To use
115 /// this feature you must first add a template specialization of
116 /// ErrorOrUserDataTraits derived from std::true_type for your type in the lld
117 /// namespace. This specialization must have a static error_code error()
118 /// function that returns the error_code this data is used with.
120 /// getError<UserData>() may be called to get either the stored user data, or
121 /// a default constructed UserData if none was stored.
125 /// struct InvalidArgError {
126 /// InvalidArgError() {}
127 /// InvalidArgError(std::string S) : ArgName(S) {}
128 /// std::string ArgName;
133 /// struct ErrorOrUserDataTraits<InvalidArgError> : std::true_type {
134 /// static error_code error() {
135 /// return make_error_code(errc::invalid_argument);
138 /// } // end namespace llvm
140 /// using namespace llvm;
142 /// ErrorOr<int> foo() {
143 /// return InvalidArgError("adena");
148 /// if (!a && error_code(a) == errc::invalid_argument)
149 /// llvm::errs() << a.getError<InvalidArgError>().ArgName << "\n";
153 /// An implicit conversion to bool provides a way to check if there was an
154 /// error. The unary * and -> operators provide pointer like access to the
155 /// value. Accessing the value when there is an error has undefined behavior.
157 /// When T is a reference type the behaivor is slightly different. The reference
158 /// is held in a std::reference_wrapper<std::remove_reference<T>::type>, and
159 /// there is special handling to make operator -> work as if T was not a
162 /// T cannot be a rvalue reference.
165 template <class OtherT> friend class ErrorOr;
166 static const bool isRef = is_reference<T>::value;
167 typedef ReferenceStorage<typename remove_reference<T>::type> wrap;
174 >::type storage_type;
177 typedef typename remove_reference<T>::type &reference;
178 typedef typename remove_reference<T>::type *pointer;
181 ErrorOr() : IsValid(false) {}
183 ErrorOr(llvm::error_code EC) : HasError(true), IsValid(true) {
184 Error = new ErrorHolderBase;
186 Error->HasUserData = false;
189 template<class UserDataT>
190 ErrorOr(UserDataT UD, typename
191 enable_if_c<ErrorOrUserDataTraits<UserDataT>::value>::type* = 0)
192 : HasError(true), IsValid(true) {
193 Error = new ErrorHolder<UserDataT>(llvm_move(UD));
194 Error->Error = ErrorOrUserDataTraits<UserDataT>::error();
195 Error->HasUserData = true;
198 ErrorOr(T Val) : HasError(false), IsValid(true) {
199 new (get()) storage_type(moveIfMoveConstructible<storage_type>(Val));
202 template <class OtherT>
203 ErrorOr(ErrorOr<OtherT> &Other) : IsValid(false) {
204 // Construct an invalid ErrorOr if other is invalid.
208 if (!Other.HasError) {
209 // Get the other value.
211 new (get()) storage_type(*Other.get());
213 // Get other's error.
220 ErrorOr &operator =(const ErrorOr &Other) {
225 new (this) ErrorOr(Other);
230 #if LLVM_HAS_RVALUE_REFERENCES
231 template <class OtherT>
232 ErrorOr(ErrorOr<OtherT> &&Other) : IsValid(false) {
233 // Construct an invalid ErrorOr if other is invalid.
237 if (!Other.HasError) {
238 // Get the other value.
240 new (get()) storage_type(std::move(*Other.get()));
241 // Tell other not to do any destruction.
242 Other.IsValid = false;
244 // Get other's error.
247 // Tell other not to do any destruction.
248 Other.IsValid = false;
252 ErrorOr &operator =(ErrorOr &&Other) {
257 new (this) ErrorOr(std::move(Other));
269 get()->~storage_type();
273 ET getError() const {
274 assert(IsValid && "Cannot get the error of a default constructed ErrorOr!");
275 assert(HasError && "Cannot get an error if none exists!");
276 assert(ErrorOrUserDataTraits<ET>::error() == Error->Error &&
277 "Incorrect user error data type for error!");
278 if (!Error->HasUserData)
280 return reinterpret_cast<const ErrorHolder<ET>*>(Error)->UserData;
283 typedef void (*unspecified_bool_type)();
284 static void unspecified_bool_true() {}
286 /// \brief Return false if there is an error.
287 operator unspecified_bool_type() const {
288 assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
289 return HasError ? 0 : unspecified_bool_true;
292 operator llvm::error_code() const {
293 assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
294 return HasError ? Error->Error : llvm::error_code::success();
297 pointer operator ->() {
298 return toPointer(get());
301 reference operator *() {
306 pointer toPointer(pointer Val) {
310 pointer toPointer(wrap *Val) {
314 storage_type *get() {
315 assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
316 assert(!HasError && "Cannot get value when an error exists!");
317 return reinterpret_cast<storage_type*>(TStorage.buffer);
320 const storage_type *get() const {
321 assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
322 assert(!HasError && "Cannot get value when an error exists!");
323 return reinterpret_cast<const storage_type*>(TStorage.buffer);
327 AlignedCharArrayUnion<storage_type> TStorage;
328 ErrorHolderBase *Error;
334 // ErrorOr specialization for void.
336 class ErrorOr<void> {
338 ErrorOr() : Error(0, 0) {}
340 ErrorOr(llvm::error_code EC) : Error(0, 0) {
341 if (EC == errc::success) {
345 ErrorHolderBase *E = new ErrorHolderBase;
347 E->HasUserData = false;
351 template<class UserDataT>
352 ErrorOr(UserDataT UD, typename
353 enable_if_c<ErrorOrUserDataTraits<UserDataT>::value>::type* = 0)
355 ErrorHolderBase *E = new ErrorHolder<UserDataT>(llvm_move(UD));
356 E->Error = ErrorOrUserDataTraits<UserDataT>::error();
357 E->HasUserData = true;
361 ErrorOr(const ErrorOr &Other) : Error(0, 0) {
363 if (Other.Error.getPointer()->Error) {
364 Error.getPointer()->aquire();
368 ErrorOr &operator =(const ErrorOr &Other) {
373 new (this) ErrorOr(Other);
378 #if LLVM_HAS_RVALUE_REFERENCES
379 ErrorOr(ErrorOr &&Other) : Error(0) {
380 // Get other's error.
382 // Tell other not to do any destruction.
383 Other.Error.setPointer(0);
386 ErrorOr &operator =(ErrorOr &&Other) {
391 new (this) ErrorOr(std::move(Other));
398 if (Error.getPointer())
399 Error.getPointer()->release();
403 ET getError() const {
404 assert(ErrorOrUserDataTraits<ET>::error() == *this &&
405 "Incorrect user error data type for error!");
406 if (!Error.getPointer()->HasUserData)
408 return reinterpret_cast<const ErrorHolder<ET> *>(
409 Error.getPointer())->UserData;
412 typedef void (*unspecified_bool_type)();
413 static void unspecified_bool_true() {}
415 /// \brief Return false if there is an error.
416 operator unspecified_bool_type() const {
417 return Error.getInt() ? unspecified_bool_true : 0;
420 operator llvm::error_code() const {
421 return Error.getInt() ? make_error_code(errc::success)
422 : Error.getPointer()->Error;
426 // If the bit is 1, the error is success.
427 llvm::PointerIntPair<ErrorHolderBase *, 1> Error;
430 template<class T, class E>
431 typename enable_if_c<is_error_code_enum<E>::value ||
432 is_error_condition_enum<E>::value, bool>::type
433 operator ==(ErrorOr<T> &Err, E Code) {
434 return error_code(Err) == Code;
436 } // end namespace llvm