1 //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines an API used to report recoverable errors.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_ERROR_H
15 #define LLVM_SUPPORT_ERROR_H
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Config/abi-breaking.h"
22 #include "llvm/Support/AlignOf.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/ErrorOr.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/raw_ostream.h"
37 #include <system_error>
38 #include <type_traits>
46 /// Base class for error info classes. Do not extend this directly: Extend
47 /// the ErrorInfo template subclass instead.
50 virtual ~ErrorInfoBase() = default;
52 /// Print an error message to an output stream.
53 virtual void log(raw_ostream &OS) const = 0;
55 /// Return the error message as a string.
56 virtual std::string message() const {
58 raw_string_ostream OS(Msg);
63 /// Convert this error to a std::error_code.
65 /// This is a temporary crutch to enable interaction with code still
66 /// using std::error_code. It will be removed in the future.
67 virtual std::error_code convertToErrorCode() const = 0;
69 // Returns the class ID for this type.
70 static const void *classID() { return &ID; }
72 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
73 virtual const void *dynamicClassID() const = 0;
75 // Check whether this instance is a subclass of the class identified by
77 virtual bool isA(const void *const ClassID) const {
78 return ClassID == classID();
81 // Check whether this instance is a subclass of ErrorInfoT.
82 template <typename ErrorInfoT> bool isA() const {
83 return isA(ErrorInfoT::classID());
87 virtual void anchor();
92 /// Lightweight error class with error context and mandatory checking.
94 /// Instances of this class wrap a ErrorInfoBase pointer. Failure states
95 /// are represented by setting the pointer to a ErrorInfoBase subclass
96 /// instance containing information describing the failure. Success is
97 /// represented by a null pointer value.
99 /// Instances of Error also contains a 'Checked' flag, which must be set
100 /// before the destructor is called, otherwise the destructor will trigger a
101 /// runtime error. This enforces at runtime the requirement that all Error
102 /// instances be checked or returned to the caller.
104 /// There are two ways to set the checked flag, depending on what state the
105 /// Error instance is in. For Error instances indicating success, it
106 /// is sufficient to invoke the boolean conversion operator. E.g.:
109 /// Error foo(<...>);
111 /// if (auto E = foo(<...>))
112 /// return E; // <- Return E if it is in the error state.
113 /// // We have verified that E was in the success state. It can now be safely
117 /// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
118 /// without testing the return value will raise a runtime error, even if foo
121 /// For Error instances representing failure, you must use either the
122 /// handleErrors or handleAllErrors function with a typed handler. E.g.:
125 /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
126 /// // Custom error info.
129 /// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
131 /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
134 /// [](const MyErrorInfo &M) {
135 /// // Deal with the error.
137 /// [](std::unique_ptr<OtherError> M) -> Error {
138 /// if (canHandle(*M)) {
140 /// return Error::success();
142 /// // Couldn't handle this error instance. Pass it up the stack.
143 /// return Error(std::move(M));
145 /// // Note - we must check or return NewE in case any of the handlers
146 /// // returned a new error.
149 /// The handleAllErrors function is identical to handleErrors, except
150 /// that it has a void return type, and requires all errors to be handled and
151 /// no new errors be returned. It prevents errors (assuming they can all be
152 /// handled) from having to be bubbled all the way to the top-level.
154 /// *All* Error instances must be checked before destruction, even if
155 /// they're moved-assigned or constructed from Success values that have already
156 /// been checked. This enforces checking through all levels of the call stack.
157 class LLVM_NODISCARD Error {
158 // ErrorList needs to be able to yank ErrorInfoBase pointers out of this
159 // class to add to the error list.
160 friend class ErrorList;
162 // handleErrors needs to be able to set the Checked flag.
163 template <typename... HandlerTs>
164 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
166 // Expected<T> needs to be able to steal the payload when constructed from an
168 template <typename T> friend class Expected;
171 /// Create a success value. Prefer using 'Error::success()' for readability
178 /// Create a success value.
179 static ErrorSuccess success();
181 // Errors are not copy-constructable.
182 Error(const Error &Other) = delete;
184 /// Move-construct an error value. The newly constructed error is considered
185 /// unchecked, even if the source error had been checked. The original error
186 /// becomes a checked Success value, regardless of its original state.
187 Error(Error &&Other) {
189 *this = std::move(Other);
192 /// Create an error value. Prefer using the 'make_error' function, but
193 /// this constructor can be useful when "re-throwing" errors from handlers.
194 Error(std::unique_ptr<ErrorInfoBase> Payload) {
195 setPtr(Payload.release());
199 // Errors are not copy-assignable.
200 Error &operator=(const Error &Other) = delete;
202 /// Move-assign an error value. The current error must represent success, you
203 /// you cannot overwrite an unhandled error. The current error is then
204 /// considered unchecked. The source error becomes a checked success value,
205 /// regardless of its original state.
206 Error &operator=(Error &&Other) {
207 // Don't allow overwriting of unchecked values.
209 setPtr(Other.getPtr());
211 // This Error is unchecked, even if the source error was checked.
214 // Null out Other's payload and set its checked bit.
215 Other.setPtr(nullptr);
216 Other.setChecked(true);
221 /// Destroy a Error. Fails with a call to abort() if the error is
228 /// Bool conversion. Returns true if this Error is in a failure state,
229 /// and false if it is in an accept state. If the error is in a Success state
230 /// it will be considered checked.
231 explicit operator bool() {
232 setChecked(getPtr() == nullptr);
233 return getPtr() != nullptr;
236 /// Check whether one error is a subclass of another.
237 template <typename ErrT> bool isA() const {
238 return getPtr() && getPtr()->isA(ErrT::classID());
241 /// Returns the dynamic class id of this error, or null if this is a success
243 const void* dynamicClassID() const {
246 return getPtr()->dynamicClassID();
250 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
251 // assertIsChecked() happens very frequently, but under normal circumstances
252 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
253 // of debug prints can cause the function to be too large for inlining. So
254 // it's important that we define this function out of line so that it can't be
256 LLVM_ATTRIBUTE_NORETURN
257 void fatalUncheckedError() const;
260 void assertIsChecked() {
261 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
262 if (LLVM_UNLIKELY(!getChecked() || getPtr()))
263 fatalUncheckedError();
267 ErrorInfoBase *getPtr() const {
268 return reinterpret_cast<ErrorInfoBase*>(
269 reinterpret_cast<uintptr_t>(Payload) &
270 ~static_cast<uintptr_t>(0x1));
273 void setPtr(ErrorInfoBase *EI) {
274 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
275 Payload = reinterpret_cast<ErrorInfoBase*>(
276 (reinterpret_cast<uintptr_t>(EI) &
277 ~static_cast<uintptr_t>(0x1)) |
278 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
284 bool getChecked() const {
285 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
286 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
292 void setChecked(bool V) {
293 Payload = reinterpret_cast<ErrorInfoBase*>(
294 (reinterpret_cast<uintptr_t>(Payload) &
295 ~static_cast<uintptr_t>(0x1)) |
299 std::unique_ptr<ErrorInfoBase> takePayload() {
300 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
306 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
307 if (auto P = E.getPtr())
314 ErrorInfoBase *Payload = nullptr;
317 /// Subclass of Error for the sole purpose of identifying the success path in
318 /// the type system. This allows to catch invalid conversion to Expected<T> at
320 class ErrorSuccess : public Error {};
322 inline ErrorSuccess Error::success() { return ErrorSuccess(); }
324 /// Make a Error instance representing failure using the given error info
326 template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
327 return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
330 /// Base class for user error types. Users should declare their error types
333 /// class MyError : public ErrorInfo<MyError> {
337 /// This class provides an implementation of the ErrorInfoBase::kind
338 /// method, which is used by the Error RTTI system.
339 template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
340 class ErrorInfo : public ParentErrT {
342 static const void *classID() { return &ThisErrT::ID; }
344 const void *dynamicClassID() const override { return &ThisErrT::ID; }
346 bool isA(const void *const ClassID) const override {
347 return ClassID == classID() || ParentErrT::isA(ClassID);
351 /// Special ErrorInfo subclass representing a list of ErrorInfos.
352 /// Instances of this class are constructed by joinError.
353 class ErrorList final : public ErrorInfo<ErrorList> {
354 // handleErrors needs to be able to iterate the payload list of an
356 template <typename... HandlerTs>
357 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
359 // joinErrors is implemented in terms of join.
360 friend Error joinErrors(Error, Error);
363 void log(raw_ostream &OS) const override {
364 OS << "Multiple errors:\n";
365 for (auto &ErrPayload : Payloads) {
371 std::error_code convertToErrorCode() const override;
373 // Used by ErrorInfo::classID.
377 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
378 std::unique_ptr<ErrorInfoBase> Payload2) {
379 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
380 "ErrorList constructor payloads should be singleton errors");
381 Payloads.push_back(std::move(Payload1));
382 Payloads.push_back(std::move(Payload2));
385 static Error join(Error E1, Error E2) {
390 if (E1.isA<ErrorList>()) {
391 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
392 if (E2.isA<ErrorList>()) {
393 auto E2Payload = E2.takePayload();
394 auto &E2List = static_cast<ErrorList &>(*E2Payload);
395 for (auto &Payload : E2List.Payloads)
396 E1List.Payloads.push_back(std::move(Payload));
398 E1List.Payloads.push_back(E2.takePayload());
402 if (E2.isA<ErrorList>()) {
403 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
404 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
407 return Error(std::unique_ptr<ErrorList>(
408 new ErrorList(E1.takePayload(), E2.takePayload())));
411 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
414 /// Concatenate errors. The resulting Error is unchecked, and contains the
415 /// ErrorInfo(s), if any, contained in E1, followed by the
416 /// ErrorInfo(s), if any, contained in E2.
417 inline Error joinErrors(Error E1, Error E2) {
418 return ErrorList::join(std::move(E1), std::move(E2));
421 /// Tagged union holding either a T or a Error.
423 /// This class parallels ErrorOr, but replaces error_code with Error. Since
424 /// Error cannot be copied, this class replaces getError() with
425 /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
426 /// error class type.
427 template <class T> class LLVM_NODISCARD Expected {
428 template <class T1> friend class ExpectedAsOutParameter;
429 template <class OtherT> friend class Expected;
431 static const bool isRef = std::is_reference<T>::value;
433 using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
435 using error_type = std::unique_ptr<ErrorInfoBase>;
438 using storage_type = typename std::conditional<isRef, wrap, T>::type;
439 using value_type = T;
442 using reference = typename std::remove_reference<T>::type &;
443 using const_reference = const typename std::remove_reference<T>::type &;
444 using pointer = typename std::remove_reference<T>::type *;
445 using const_pointer = const typename std::remove_reference<T>::type *;
448 /// Create an Expected<T> error value from the given Error.
451 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
452 // Expected is unchecked upon construction in Debug builds.
456 assert(Err && "Cannot create Expected<T> from Error success value.");
457 new (getErrorStorage()) error_type(Err.takePayload());
460 /// Forbid to convert from Error::success() implicitly, this avoids having
461 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
462 /// but triggers the assertion above.
463 Expected(ErrorSuccess) = delete;
465 /// Create an Expected<T> success value from the given OtherT value, which
466 /// must be convertible to T.
467 template <typename OtherT>
468 Expected(OtherT &&Val,
469 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
472 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
473 // Expected is unchecked upon construction in Debug builds.
477 new (getStorage()) storage_type(std::forward<OtherT>(Val));
480 /// Move construct an Expected<T> value.
481 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
483 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
484 /// must be convertible to T.
485 template <class OtherT>
486 Expected(Expected<OtherT> &&Other,
487 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
489 moveConstruct(std::move(Other));
492 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
493 /// isn't convertible to T.
494 template <class OtherT>
496 Expected<OtherT> &&Other,
497 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
499 moveConstruct(std::move(Other));
502 /// Move-assign from another Expected<T>.
503 Expected &operator=(Expected &&Other) {
504 moveAssign(std::move(Other));
508 /// Destroy an Expected<T>.
512 getStorage()->~storage_type();
514 getErrorStorage()->~error_type();
517 /// Return false if there is an error.
518 explicit operator bool() {
519 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
520 Unchecked = HasError;
525 /// Returns a reference to the stored T value.
528 return *getStorage();
531 /// Returns a const reference to the stored T value.
532 const_reference get() const {
534 return const_cast<Expected<T> *>(this)->get();
537 /// Check that this Expected<T> is an error of type ErrT.
538 template <typename ErrT> bool errorIsA() const {
539 return HasError && (*getErrorStorage())->template isA<ErrT>();
542 /// Take ownership of the stored error.
543 /// After calling this the Expected<T> is in an indeterminate state that can
544 /// only be safely destructed. No further calls (beside the destructor) should
545 /// be made on the Expected<T> vaule.
547 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
550 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
553 /// Returns a pointer to the stored T value.
554 pointer operator->() {
556 return toPointer(getStorage());
559 /// Returns a const pointer to the stored T value.
560 const_pointer operator->() const {
562 return toPointer(getStorage());
565 /// Returns a reference to the stored T value.
566 reference operator*() {
568 return *getStorage();
571 /// Returns a const reference to the stored T value.
572 const_reference operator*() const {
574 return *getStorage();
579 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
583 template <class T1, class T2>
584 static bool compareThisIfSameType(const T1 &a, const T2 &b) {
588 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
589 HasError = Other.HasError;
590 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
592 Other.Unchecked = false;
596 new (getStorage()) storage_type(std::move(*Other.getStorage()));
598 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
601 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
604 if (compareThisIfSameType(*this, Other))
608 new (this) Expected(std::move(Other));
611 pointer toPointer(pointer Val) { return Val; }
613 const_pointer toPointer(const_pointer Val) const { return Val; }
615 pointer toPointer(wrap *Val) { return &Val->get(); }
617 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
619 storage_type *getStorage() {
620 assert(!HasError && "Cannot get value when an error exists!");
621 return reinterpret_cast<storage_type *>(TStorage.buffer);
624 const storage_type *getStorage() const {
625 assert(!HasError && "Cannot get value when an error exists!");
626 return reinterpret_cast<const storage_type *>(TStorage.buffer);
629 error_type *getErrorStorage() {
630 assert(HasError && "Cannot get error when a value exists!");
631 return reinterpret_cast<error_type *>(ErrorStorage.buffer);
634 const error_type *getErrorStorage() const {
635 assert(HasError && "Cannot get error when a value exists!");
636 return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
639 // Used by ExpectedAsOutParameter to reset the checked flag.
640 void setUnchecked() {
641 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
646 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
647 LLVM_ATTRIBUTE_NORETURN
648 LLVM_ATTRIBUTE_NOINLINE
649 void fatalUncheckedExpected() const {
650 dbgs() << "Expected<T> must be checked before access or destruction.\n";
652 dbgs() << "Unchecked Expected<T> contained error:\n";
653 (*getErrorStorage())->log(dbgs());
655 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
656 "values in success mode must still be checked prior to being "
662 void assertIsChecked() {
663 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
664 if (LLVM_UNLIKELY(Unchecked))
665 fatalUncheckedExpected();
670 AlignedCharArrayUnion<storage_type> TStorage;
671 AlignedCharArrayUnion<error_type> ErrorStorage;
674 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
679 /// Report a serious error, calling any installed error handler. See
681 LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err,
682 bool gen_crash_diag = true);
684 /// Report a fatal error if Err is a failure value.
686 /// This function can be used to wrap calls to fallible functions ONLY when it
687 /// is known that the Error will always be a success value. E.g.
690 /// // foo only attempts the fallible operation if DoFallibleOperation is
691 /// // true. If DoFallibleOperation is false then foo always returns
692 /// // Error::success().
693 /// Error foo(bool DoFallibleOperation);
695 /// cantFail(foo(false));
697 inline void cantFail(Error Err, const char *Msg = nullptr) {
700 Msg = "Failure value returned from cantFail wrapped call";
701 llvm_unreachable(Msg);
705 /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
706 /// returns the contained value.
708 /// This function can be used to wrap calls to fallible functions ONLY when it
709 /// is known that the Error will always be a success value. E.g.
712 /// // foo only attempts the fallible operation if DoFallibleOperation is
713 /// // true. If DoFallibleOperation is false then foo always returns an int.
714 /// Expected<int> foo(bool DoFallibleOperation);
716 /// int X = cantFail(foo(false));
718 template <typename T>
719 T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
721 return std::move(*ValOrErr);
724 Msg = "Failure value returned from cantFail wrapped call";
725 llvm_unreachable(Msg);
729 /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
730 /// returns the contained reference.
732 /// This function can be used to wrap calls to fallible functions ONLY when it
733 /// is known that the Error will always be a success value. E.g.
736 /// // foo only attempts the fallible operation if DoFallibleOperation is
737 /// // true. If DoFallibleOperation is false then foo always returns a Bar&.
738 /// Expected<Bar&> foo(bool DoFallibleOperation);
740 /// Bar &X = cantFail(foo(false));
742 template <typename T>
743 T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
748 Msg = "Failure value returned from cantFail wrapped call";
749 llvm_unreachable(Msg);
753 /// Helper for testing applicability of, and applying, handlers for
755 template <typename HandlerT>
756 class ErrorHandlerTraits
757 : public ErrorHandlerTraits<decltype(
758 &std::remove_reference<HandlerT>::type::operator())> {};
760 // Specialization functions of the form 'Error (const ErrT&)'.
761 template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
763 static bool appliesTo(const ErrorInfoBase &E) {
764 return E.template isA<ErrT>();
767 template <typename HandlerT>
768 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
769 assert(appliesTo(*E) && "Applying incorrect handler");
770 return H(static_cast<ErrT &>(*E));
774 // Specialization functions of the form 'void (const ErrT&)'.
775 template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
777 static bool appliesTo(const ErrorInfoBase &E) {
778 return E.template isA<ErrT>();
781 template <typename HandlerT>
782 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
783 assert(appliesTo(*E) && "Applying incorrect handler");
784 H(static_cast<ErrT &>(*E));
785 return Error::success();
789 /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
790 template <typename ErrT>
791 class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
793 static bool appliesTo(const ErrorInfoBase &E) {
794 return E.template isA<ErrT>();
797 template <typename HandlerT>
798 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
799 assert(appliesTo(*E) && "Applying incorrect handler");
800 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
801 return H(std::move(SubE));
805 /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
806 template <typename ErrT>
807 class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
809 static bool appliesTo(const ErrorInfoBase &E) {
810 return E.template isA<ErrT>();
813 template <typename HandlerT>
814 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
815 assert(appliesTo(*E) && "Applying incorrect handler");
816 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
818 return Error::success();
822 // Specialization for member functions of the form 'RetT (const ErrT&)'.
823 template <typename C, typename RetT, typename ErrT>
824 class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
825 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
827 // Specialization for member functions of the form 'RetT (const ErrT&) const'.
828 template <typename C, typename RetT, typename ErrT>
829 class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
830 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
832 // Specialization for member functions of the form 'RetT (const ErrT&)'.
833 template <typename C, typename RetT, typename ErrT>
834 class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
835 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
837 // Specialization for member functions of the form 'RetT (const ErrT&) const'.
838 template <typename C, typename RetT, typename ErrT>
839 class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
840 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
842 /// Specialization for member functions of the form
843 /// 'RetT (std::unique_ptr<ErrT>)'.
844 template <typename C, typename RetT, typename ErrT>
845 class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
846 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
848 /// Specialization for member functions of the form
849 /// 'RetT (std::unique_ptr<ErrT>) const'.
850 template <typename C, typename RetT, typename ErrT>
851 class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
852 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
854 inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
855 return Error(std::move(Payload));
858 template <typename HandlerT, typename... HandlerTs>
859 Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
860 HandlerT &&Handler, HandlerTs &&... Handlers) {
861 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
862 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
864 return handleErrorImpl(std::move(Payload),
865 std::forward<HandlerTs>(Handlers)...);
868 /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
869 /// unhandled errors (or Errors returned by handlers) are re-concatenated and
871 /// Because this function returns an error, its result must also be checked
872 /// or returned. If you intend to handle all errors use handleAllErrors
873 /// (which returns void, and will abort() on unhandled errors) instead.
874 template <typename... HandlerTs>
875 Error handleErrors(Error E, HandlerTs &&... Hs) {
877 return Error::success();
879 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
881 if (Payload->isA<ErrorList>()) {
882 ErrorList &List = static_cast<ErrorList &>(*Payload);
884 for (auto &P : List.Payloads)
887 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
891 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
894 /// Behaves the same as handleErrors, except that by contract all errors
895 /// *must* be handled by the given handlers (i.e. there must be no remaining
896 /// errors after running the handlers, or llvm_unreachable is called).
897 template <typename... HandlerTs>
898 void handleAllErrors(Error E, HandlerTs &&... Handlers) {
899 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
902 /// Check that E is a non-error, then drop it.
903 /// If E is an error, llvm_unreachable will be called.
904 inline void handleAllErrors(Error E) {
905 cantFail(std::move(E));
908 /// Handle any errors (if present) in an Expected<T>, then try a recovery path.
910 /// If the incoming value is a success value it is returned unmodified. If it
911 /// is a failure value then it the contained error is passed to handleErrors.
912 /// If handleErrors is able to handle the error then the RecoveryPath functor
913 /// is called to supply the final result. If handleErrors is not able to
914 /// handle all errors then the unhandled errors are returned.
916 /// This utility enables the follow pattern:
919 /// enum FooStrategy { Aggressive, Conservative };
920 /// Expected<Foo> foo(FooStrategy S);
922 /// auto ResultOrErr =
925 /// []() { return foo(Conservative); },
926 /// [](AggressiveStrategyError&) {
927 /// // Implicitly conusme this - we'll recover by using a conservative
932 template <typename T, typename RecoveryFtor, typename... HandlerTs>
933 Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
934 HandlerTs &&... Handlers) {
938 if (auto Err = handleErrors(ValOrErr.takeError(),
939 std::forward<HandlerTs>(Handlers)...))
940 return std::move(Err);
942 return RecoveryPath();
945 /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
946 /// will be printed before the first one is logged. A newline will be printed
947 /// after each error.
949 /// This is useful in the base level of your program to allow clean termination
950 /// (allowing clean deallocation of resources, etc.), while reporting error
951 /// information to the user.
952 void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
954 /// Write all error messages (if any) in E to a string. The newline character
955 /// is used to separate error messages.
956 inline std::string toString(Error E) {
957 SmallVector<std::string, 2> Errors;
958 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
959 Errors.push_back(EI.message());
961 return join(Errors.begin(), Errors.end(), "\n");
964 /// Consume a Error without doing anything. This method should be used
965 /// only where an error can be considered a reasonable and expected return
968 /// Uses of this method are potentially indicative of design problems: If it's
969 /// legitimate to do nothing while processing an "error", the error-producer
970 /// might be more clearly refactored to return an Optional<T>.
971 inline void consumeError(Error Err) {
972 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
975 /// Helper for converting an Error to a bool.
977 /// This method returns true if Err is in an error state, or false if it is
978 /// in a success state. Puts Err in a checked state in both cases (unlike
979 /// Error::operator bool(), which only does this for success states).
980 inline bool errorToBool(Error Err) {
981 bool IsError = static_cast<bool>(Err);
983 consumeError(std::move(Err));
987 /// Helper for Errors used as out-parameters.
989 /// This helper is for use with the Error-as-out-parameter idiom, where an error
990 /// is passed to a function or method by reference, rather than being returned.
991 /// In such cases it is helpful to set the checked bit on entry to the function
992 /// so that the error can be written to (unchecked Errors abort on assignment)
993 /// and clear the checked bit on exit so that clients cannot accidentally forget
994 /// to check the result. This helper performs these actions automatically using
998 /// Result foo(Error &Err) {
999 /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1000 /// // <body of foo>
1001 /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1005 /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1006 /// used with optional Errors (Error pointers that are allowed to be null). If
1007 /// ErrorAsOutParameter took an Error reference, an instance would have to be
1008 /// created inside every condition that verified that Error was non-null. By
1009 /// taking an Error pointer we can just create one instance at the top of the
1011 class ErrorAsOutParameter {
1013 ErrorAsOutParameter(Error *Err) : Err(Err) {
1014 // Raise the checked bit if Err is success.
1019 ~ErrorAsOutParameter() {
1020 // Clear the checked bit.
1022 *Err = Error::success();
1029 /// Helper for Expected<T>s used as out-parameters.
1031 /// See ErrorAsOutParameter.
1032 template <typename T>
1033 class ExpectedAsOutParameter {
1035 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1036 : ValOrErr(ValOrErr) {
1041 ~ExpectedAsOutParameter() {
1043 ValOrErr->setUnchecked();
1047 Expected<T> *ValOrErr;
1050 /// This class wraps a std::error_code in a Error.
1052 /// This is useful if you're writing an interface that returns a Error
1053 /// (or Expected) and you want to call code that still returns
1054 /// std::error_codes.
1055 class ECError : public ErrorInfo<ECError> {
1056 friend Error errorCodeToError(std::error_code);
1059 void setErrorCode(std::error_code EC) { this->EC = EC; }
1060 std::error_code convertToErrorCode() const override { return EC; }
1061 void log(raw_ostream &OS) const override { OS << EC.message(); }
1063 // Used by ErrorInfo::classID.
1067 ECError() = default;
1068 ECError(std::error_code EC) : EC(EC) {}
1073 /// The value returned by this function can be returned from convertToErrorCode
1074 /// for Error values where no sensible translation to std::error_code exists.
1075 /// It should only be used in this situation, and should never be used where a
1076 /// sensible conversion to std::error_code is available, as attempts to convert
1077 /// to/from this error will result in a fatal error. (i.e. it is a programmatic
1078 ///error to try to convert such a value).
1079 std::error_code inconvertibleErrorCode();
1081 /// Helper for converting an std::error_code to a Error.
1082 Error errorCodeToError(std::error_code EC);
1084 /// Helper for converting an ECError to a std::error_code.
1086 /// This method requires that Err be Error() or an ECError, otherwise it
1087 /// will trigger a call to abort().
1088 std::error_code errorToErrorCode(Error Err);
1090 /// Convert an ErrorOr<T> to an Expected<T>.
1091 template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1092 if (auto EC = EO.getError())
1093 return errorCodeToError(EC);
1094 return std::move(*EO);
1097 /// Convert an Expected<T> to an ErrorOr<T>.
1098 template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1099 if (auto Err = E.takeError())
1100 return errorToErrorCode(std::move(Err));
1101 return std::move(*E);
1104 /// This class wraps a string in an Error.
1106 /// StringError is useful in cases where the client is not expected to be able
1107 /// to consume the specific error message programmatically (for example, if the
1108 /// error message is to be presented to the user).
1109 class StringError : public ErrorInfo<StringError> {
1113 StringError(const Twine &S, std::error_code EC);
1115 void log(raw_ostream &OS) const override;
1116 std::error_code convertToErrorCode() const override;
1118 const std::string &getMessage() const { return Msg; }
1125 /// Create formatted StringError object.
1126 template <typename... Ts>
1127 Error createStringError(std::error_code EC, char const *Fmt,
1128 const Ts &... Vals) {
1130 raw_string_ostream Stream(Buffer);
1131 Stream << format(Fmt, Vals...);
1132 return make_error<StringError>(Stream.str(), EC);
1135 Error createStringError(std::error_code EC, char const *Msg);
1137 /// Helper for check-and-exit error handling.
1139 /// For tool use only. NOT FOR USE IN LIBRARY CODE.
1143 /// Create an error on exit helper.
1144 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1145 : Banner(std::move(Banner)),
1146 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1148 /// Set the banner string for any errors caught by operator().
1149 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1151 /// Set the exit-code mapper function.
1152 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1153 this->GetExitCode = std::move(GetExitCode);
1156 /// Check Err. If it's in a failure state log the error(s) and exit.
1157 void operator()(Error Err) const { checkError(std::move(Err)); }
1159 /// Check E. If it's in a success state then return the contained value. If
1160 /// it's in a failure state log the error(s) and exit.
1161 template <typename T> T operator()(Expected<T> &&E) const {
1162 checkError(E.takeError());
1163 return std::move(*E);
1166 /// Check E. If it's in a success state then return the contained reference. If
1167 /// it's in a failure state log the error(s) and exit.
1168 template <typename T> T& operator()(Expected<T&> &&E) const {
1169 checkError(E.takeError());
1174 void checkError(Error Err) const {
1176 int ExitCode = GetExitCode(Err);
1177 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1183 std::function<int(const Error &)> GetExitCode;
1186 } // end namespace llvm
1188 #endif // LLVM_SUPPORT_ERROR_H