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/raw_ostream.h"
36 #include <system_error>
37 #include <type_traits>
45 /// Base class for error info classes. Do not extend this directly: Extend
46 /// the ErrorInfo template subclass instead.
49 virtual ~ErrorInfoBase() = default;
51 /// Print an error message to an output stream.
52 virtual void log(raw_ostream &OS) const = 0;
54 /// Return the error message as a string.
55 virtual std::string message() const {
57 raw_string_ostream OS(Msg);
62 /// Convert this error to a std::error_code.
64 /// This is a temporary crutch to enable interaction with code still
65 /// using std::error_code. It will be removed in the future.
66 virtual std::error_code convertToErrorCode() const = 0;
68 // Returns the class ID for this type.
69 static const void *classID() { return &ID; }
71 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
72 virtual const void *dynamicClassID() const = 0;
74 // Check whether this instance is a subclass of the class identified by
76 virtual bool isA(const void *const ClassID) const {
77 return ClassID == classID();
80 // Check whether this instance is a subclass of ErrorInfoT.
81 template <typename ErrorInfoT> bool isA() const {
82 return isA(ErrorInfoT::classID());
86 virtual void anchor();
91 /// Lightweight error class with error context and mandatory checking.
93 /// Instances of this class wrap a ErrorInfoBase pointer. Failure states
94 /// are represented by setting the pointer to a ErrorInfoBase subclass
95 /// instance containing information describing the failure. Success is
96 /// represented by a null pointer value.
98 /// Instances of Error also contains a 'Checked' flag, which must be set
99 /// before the destructor is called, otherwise the destructor will trigger a
100 /// runtime error. This enforces at runtime the requirement that all Error
101 /// instances be checked or returned to the caller.
103 /// There are two ways to set the checked flag, depending on what state the
104 /// Error instance is in. For Error instances indicating success, it
105 /// is sufficient to invoke the boolean conversion operator. E.g.:
108 /// Error foo(<...>);
110 /// if (auto E = foo(<...>))
111 /// return E; // <- Return E if it is in the error state.
112 /// // We have verified that E was in the success state. It can now be safely
116 /// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
117 /// without testing the return value will raise a runtime error, even if foo
120 /// For Error instances representing failure, you must use either the
121 /// handleErrors or handleAllErrors function with a typed handler. E.g.:
124 /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
125 /// // Custom error info.
128 /// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
130 /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
133 /// [](const MyErrorInfo &M) {
134 /// // Deal with the error.
136 /// [](std::unique_ptr<OtherError> M) -> Error {
137 /// if (canHandle(*M)) {
139 /// return Error::success();
141 /// // Couldn't handle this error instance. Pass it up the stack.
142 /// return Error(std::move(M));
144 /// // Note - we must check or return NewE in case any of the handlers
145 /// // returned a new error.
148 /// The handleAllErrors function is identical to handleErrors, except
149 /// that it has a void return type, and requires all errors to be handled and
150 /// no new errors be returned. It prevents errors (assuming they can all be
151 /// handled) from having to be bubbled all the way to the top-level.
153 /// *All* Error instances must be checked before destruction, even if
154 /// they're moved-assigned or constructed from Success values that have already
155 /// been checked. This enforces checking through all levels of the call stack.
156 class LLVM_NODISCARD Error {
157 // ErrorList needs to be able to yank ErrorInfoBase pointers out of this
158 // class to add to the error list.
159 friend class ErrorList;
161 // handleErrors needs to be able to set the Checked flag.
162 template <typename... HandlerTs>
163 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
165 // Expected<T> needs to be able to steal the payload when constructed from an
167 template <typename T> friend class Expected;
170 /// Create a success value. Prefer using 'Error::success()' for readability
177 /// Create a success value.
178 static ErrorSuccess success();
180 // Errors are not copy-constructable.
181 Error(const Error &Other) = delete;
183 /// Move-construct an error value. The newly constructed error is considered
184 /// unchecked, even if the source error had been checked. The original error
185 /// becomes a checked Success value, regardless of its original state.
186 Error(Error &&Other) {
188 *this = std::move(Other);
191 /// Create an error value. Prefer using the 'make_error' function, but
192 /// this constructor can be useful when "re-throwing" errors from handlers.
193 Error(std::unique_ptr<ErrorInfoBase> Payload) {
194 setPtr(Payload.release());
198 // Errors are not copy-assignable.
199 Error &operator=(const Error &Other) = delete;
201 /// Move-assign an error value. The current error must represent success, you
202 /// you cannot overwrite an unhandled error. The current error is then
203 /// considered unchecked. The source error becomes a checked success value,
204 /// regardless of its original state.
205 Error &operator=(Error &&Other) {
206 // Don't allow overwriting of unchecked values.
208 setPtr(Other.getPtr());
210 // This Error is unchecked, even if the source error was checked.
213 // Null out Other's payload and set its checked bit.
214 Other.setPtr(nullptr);
215 Other.setChecked(true);
220 /// Destroy a Error. Fails with a call to abort() if the error is
227 /// Bool conversion. Returns true if this Error is in a failure state,
228 /// and false if it is in an accept state. If the error is in a Success state
229 /// it will be considered checked.
230 explicit operator bool() {
231 setChecked(getPtr() == nullptr);
232 return getPtr() != nullptr;
235 /// Check whether one error is a subclass of another.
236 template <typename ErrT> bool isA() const {
237 return getPtr() && getPtr()->isA(ErrT::classID());
240 /// Returns the dynamic class id of this error, or null if this is a success
242 const void* dynamicClassID() const {
245 return getPtr()->dynamicClassID();
249 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
250 // assertIsChecked() happens very frequently, but under normal circumstances
251 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
252 // of debug prints can cause the function to be too large for inlining. So
253 // it's important that we define this function out of line so that it can't be
255 LLVM_ATTRIBUTE_NORETURN
256 void fatalUncheckedError() const;
259 void assertIsChecked() {
260 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
261 if (LLVM_UNLIKELY(!getChecked() || getPtr()))
262 fatalUncheckedError();
266 ErrorInfoBase *getPtr() const {
267 return reinterpret_cast<ErrorInfoBase*>(
268 reinterpret_cast<uintptr_t>(Payload) &
269 ~static_cast<uintptr_t>(0x1));
272 void setPtr(ErrorInfoBase *EI) {
273 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
274 Payload = reinterpret_cast<ErrorInfoBase*>(
275 (reinterpret_cast<uintptr_t>(EI) &
276 ~static_cast<uintptr_t>(0x1)) |
277 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
283 bool getChecked() const {
284 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
285 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
291 void setChecked(bool V) {
292 Payload = reinterpret_cast<ErrorInfoBase*>(
293 (reinterpret_cast<uintptr_t>(Payload) &
294 ~static_cast<uintptr_t>(0x1)) |
298 std::unique_ptr<ErrorInfoBase> takePayload() {
299 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
305 ErrorInfoBase *Payload = nullptr;
308 /// Subclass of Error for the sole purpose of identifying the success path in
309 /// the type system. This allows to catch invalid conversion to Expected<T> at
311 class ErrorSuccess : public Error {};
313 inline ErrorSuccess Error::success() { return ErrorSuccess(); }
315 /// Make a Error instance representing failure using the given error info
317 template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
318 return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
321 /// Base class for user error types. Users should declare their error types
324 /// class MyError : public ErrorInfo<MyError> {
328 /// This class provides an implementation of the ErrorInfoBase::kind
329 /// method, which is used by the Error RTTI system.
330 template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
331 class ErrorInfo : public ParentErrT {
333 static const void *classID() { return &ThisErrT::ID; }
335 const void *dynamicClassID() const override { return &ThisErrT::ID; }
337 bool isA(const void *const ClassID) const override {
338 return ClassID == classID() || ParentErrT::isA(ClassID);
342 /// Special ErrorInfo subclass representing a list of ErrorInfos.
343 /// Instances of this class are constructed by joinError.
344 class ErrorList final : public ErrorInfo<ErrorList> {
345 // handleErrors needs to be able to iterate the payload list of an
347 template <typename... HandlerTs>
348 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
350 // joinErrors is implemented in terms of join.
351 friend Error joinErrors(Error, Error);
354 void log(raw_ostream &OS) const override {
355 OS << "Multiple errors:\n";
356 for (auto &ErrPayload : Payloads) {
362 std::error_code convertToErrorCode() const override;
364 // Used by ErrorInfo::classID.
368 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
369 std::unique_ptr<ErrorInfoBase> Payload2) {
370 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
371 "ErrorList constructor payloads should be singleton errors");
372 Payloads.push_back(std::move(Payload1));
373 Payloads.push_back(std::move(Payload2));
376 static Error join(Error E1, Error E2) {
381 if (E1.isA<ErrorList>()) {
382 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
383 if (E2.isA<ErrorList>()) {
384 auto E2Payload = E2.takePayload();
385 auto &E2List = static_cast<ErrorList &>(*E2Payload);
386 for (auto &Payload : E2List.Payloads)
387 E1List.Payloads.push_back(std::move(Payload));
389 E1List.Payloads.push_back(E2.takePayload());
393 if (E2.isA<ErrorList>()) {
394 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
395 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
398 return Error(std::unique_ptr<ErrorList>(
399 new ErrorList(E1.takePayload(), E2.takePayload())));
402 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
405 /// Concatenate errors. The resulting Error is unchecked, and contains the
406 /// ErrorInfo(s), if any, contained in E1, followed by the
407 /// ErrorInfo(s), if any, contained in E2.
408 inline Error joinErrors(Error E1, Error E2) {
409 return ErrorList::join(std::move(E1), std::move(E2));
412 /// Tagged union holding either a T or a Error.
414 /// This class parallels ErrorOr, but replaces error_code with Error. Since
415 /// Error cannot be copied, this class replaces getError() with
416 /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
417 /// error class type.
418 template <class T> class LLVM_NODISCARD Expected {
419 template <class T1> friend class ExpectedAsOutParameter;
420 template <class OtherT> friend class Expected;
422 static const bool isRef = std::is_reference<T>::value;
424 using wrap = ReferenceStorage<typename std::remove_reference<T>::type>;
426 using error_type = std::unique_ptr<ErrorInfoBase>;
429 using storage_type = typename std::conditional<isRef, wrap, T>::type;
430 using value_type = T;
433 using reference = typename std::remove_reference<T>::type &;
434 using const_reference = const typename std::remove_reference<T>::type &;
435 using pointer = typename std::remove_reference<T>::type *;
436 using const_pointer = const typename std::remove_reference<T>::type *;
439 /// Create an Expected<T> error value from the given Error.
442 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
443 // Expected is unchecked upon construction in Debug builds.
447 assert(Err && "Cannot create Expected<T> from Error success value.");
448 new (getErrorStorage()) error_type(Err.takePayload());
451 /// Forbid to convert from Error::success() implicitly, this avoids having
452 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
453 /// but triggers the assertion above.
454 Expected(ErrorSuccess) = delete;
456 /// Create an Expected<T> success value from the given OtherT value, which
457 /// must be convertible to T.
458 template <typename OtherT>
459 Expected(OtherT &&Val,
460 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
463 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
464 // Expected is unchecked upon construction in Debug builds.
468 new (getStorage()) storage_type(std::forward<OtherT>(Val));
471 /// Move construct an Expected<T> value.
472 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
474 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
475 /// must be convertible to T.
476 template <class OtherT>
477 Expected(Expected<OtherT> &&Other,
478 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
480 moveConstruct(std::move(Other));
483 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
484 /// isn't convertible to T.
485 template <class OtherT>
487 Expected<OtherT> &&Other,
488 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
490 moveConstruct(std::move(Other));
493 /// Move-assign from another Expected<T>.
494 Expected &operator=(Expected &&Other) {
495 moveAssign(std::move(Other));
499 /// Destroy an Expected<T>.
503 getStorage()->~storage_type();
505 getErrorStorage()->~error_type();
508 /// \brief Return false if there is an error.
509 explicit operator bool() {
510 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
511 Unchecked = HasError;
516 /// \brief Returns a reference to the stored T value.
519 return *getStorage();
522 /// \brief Returns a const reference to the stored T value.
523 const_reference get() const {
525 return const_cast<Expected<T> *>(this)->get();
528 /// \brief Check that this Expected<T> is an error of type ErrT.
529 template <typename ErrT> bool errorIsA() const {
530 return HasError && (*getErrorStorage())->template isA<ErrT>();
533 /// \brief Take ownership of the stored error.
534 /// After calling this the Expected<T> is in an indeterminate state that can
535 /// only be safely destructed. No further calls (beside the destructor) should
536 /// be made on the Expected<T> vaule.
538 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
541 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
544 /// \brief Returns a pointer to the stored T value.
545 pointer operator->() {
547 return toPointer(getStorage());
550 /// \brief Returns a const pointer to the stored T value.
551 const_pointer operator->() const {
553 return toPointer(getStorage());
556 /// \brief Returns a reference to the stored T value.
557 reference operator*() {
559 return *getStorage();
562 /// \brief Returns a const reference to the stored T value.
563 const_reference operator*() const {
565 return *getStorage();
570 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
574 template <class T1, class T2>
575 static bool compareThisIfSameType(const T1 &a, const T2 &b) {
579 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
580 HasError = Other.HasError;
581 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
583 Other.Unchecked = false;
587 new (getStorage()) storage_type(std::move(*Other.getStorage()));
589 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
592 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
595 if (compareThisIfSameType(*this, Other))
599 new (this) Expected(std::move(Other));
602 pointer toPointer(pointer Val) { return Val; }
604 const_pointer toPointer(const_pointer Val) const { return Val; }
606 pointer toPointer(wrap *Val) { return &Val->get(); }
608 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
610 storage_type *getStorage() {
611 assert(!HasError && "Cannot get value when an error exists!");
612 return reinterpret_cast<storage_type *>(TStorage.buffer);
615 const storage_type *getStorage() const {
616 assert(!HasError && "Cannot get value when an error exists!");
617 return reinterpret_cast<const storage_type *>(TStorage.buffer);
620 error_type *getErrorStorage() {
621 assert(HasError && "Cannot get error when a value exists!");
622 return reinterpret_cast<error_type *>(ErrorStorage.buffer);
625 const error_type *getErrorStorage() const {
626 assert(HasError && "Cannot get error when a value exists!");
627 return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
630 // Used by ExpectedAsOutParameter to reset the checked flag.
631 void setUnchecked() {
632 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
637 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
638 LLVM_ATTRIBUTE_NORETURN
639 LLVM_ATTRIBUTE_NOINLINE
640 void fatalUncheckedExpected() const {
641 dbgs() << "Expected<T> must be checked before access or destruction.\n";
643 dbgs() << "Unchecked Expected<T> contained error:\n";
644 (*getErrorStorage())->log(dbgs());
646 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
647 "values in success mode must still be checked prior to being "
653 void assertIsChecked() {
654 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
655 if (LLVM_UNLIKELY(Unchecked))
656 fatalUncheckedExpected();
661 AlignedCharArrayUnion<storage_type> TStorage;
662 AlignedCharArrayUnion<error_type> ErrorStorage;
665 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
670 /// Report a serious error, calling any installed error handler. See
672 LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err,
673 bool gen_crash_diag = true);
675 /// Report a fatal error if Err is a failure value.
677 /// This function can be used to wrap calls to fallible functions ONLY when it
678 /// is known that the Error will always be a success value. E.g.
681 /// // foo only attempts the fallible operation if DoFallibleOperation is
682 /// // true. If DoFallibleOperation is false then foo always returns
683 /// // Error::success().
684 /// Error foo(bool DoFallibleOperation);
686 /// cantFail(foo(false));
688 inline void cantFail(Error Err, const char *Msg = nullptr) {
691 Msg = "Failure value returned from cantFail wrapped call";
692 llvm_unreachable(Msg);
696 /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
697 /// returns the contained value.
699 /// This function can be used to wrap calls to fallible functions ONLY when it
700 /// is known that the Error will always be a success value. E.g.
703 /// // foo only attempts the fallible operation if DoFallibleOperation is
704 /// // true. If DoFallibleOperation is false then foo always returns an int.
705 /// Expected<int> foo(bool DoFallibleOperation);
707 /// int X = cantFail(foo(false));
709 template <typename T>
710 T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
712 return std::move(*ValOrErr);
715 Msg = "Failure value returned from cantFail wrapped call";
716 llvm_unreachable(Msg);
720 /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
721 /// returns the contained reference.
723 /// This function can be used to wrap calls to fallible functions ONLY when it
724 /// is known that the Error will always be a success value. E.g.
727 /// // foo only attempts the fallible operation if DoFallibleOperation is
728 /// // true. If DoFallibleOperation is false then foo always returns a Bar&.
729 /// Expected<Bar&> foo(bool DoFallibleOperation);
731 /// Bar &X = cantFail(foo(false));
733 template <typename T>
734 T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
739 Msg = "Failure value returned from cantFail wrapped call";
740 llvm_unreachable(Msg);
744 /// Helper for testing applicability of, and applying, handlers for
746 template <typename HandlerT>
747 class ErrorHandlerTraits
748 : public ErrorHandlerTraits<decltype(
749 &std::remove_reference<HandlerT>::type::operator())> {};
751 // Specialization functions of the form 'Error (const ErrT&)'.
752 template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
754 static bool appliesTo(const ErrorInfoBase &E) {
755 return E.template isA<ErrT>();
758 template <typename HandlerT>
759 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
760 assert(appliesTo(*E) && "Applying incorrect handler");
761 return H(static_cast<ErrT &>(*E));
765 // Specialization functions of the form 'void (const ErrT&)'.
766 template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
768 static bool appliesTo(const ErrorInfoBase &E) {
769 return E.template isA<ErrT>();
772 template <typename HandlerT>
773 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
774 assert(appliesTo(*E) && "Applying incorrect handler");
775 H(static_cast<ErrT &>(*E));
776 return Error::success();
780 /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
781 template <typename ErrT>
782 class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
784 static bool appliesTo(const ErrorInfoBase &E) {
785 return E.template isA<ErrT>();
788 template <typename HandlerT>
789 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
790 assert(appliesTo(*E) && "Applying incorrect handler");
791 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
792 return H(std::move(SubE));
796 /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
797 template <typename ErrT>
798 class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
800 static bool appliesTo(const ErrorInfoBase &E) {
801 return E.template isA<ErrT>();
804 template <typename HandlerT>
805 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
806 assert(appliesTo(*E) && "Applying incorrect handler");
807 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
809 return Error::success();
813 // Specialization for member functions of the form 'RetT (const ErrT&)'.
814 template <typename C, typename RetT, typename ErrT>
815 class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
816 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
818 // Specialization for member functions of the form 'RetT (const ErrT&) const'.
819 template <typename C, typename RetT, typename ErrT>
820 class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
821 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
823 // Specialization for member functions of the form 'RetT (const ErrT&)'.
824 template <typename C, typename RetT, typename ErrT>
825 class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
826 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
828 // Specialization for member functions of the form 'RetT (const ErrT&) const'.
829 template <typename C, typename RetT, typename ErrT>
830 class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
831 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
833 /// Specialization for member functions of the form
834 /// 'RetT (std::unique_ptr<ErrT>)'.
835 template <typename C, typename RetT, typename ErrT>
836 class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
837 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
839 /// Specialization for member functions of the form
840 /// 'RetT (std::unique_ptr<ErrT>) const'.
841 template <typename C, typename RetT, typename ErrT>
842 class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
843 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
845 inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
846 return Error(std::move(Payload));
849 template <typename HandlerT, typename... HandlerTs>
850 Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
851 HandlerT &&Handler, HandlerTs &&... Handlers) {
852 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
853 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
855 return handleErrorImpl(std::move(Payload),
856 std::forward<HandlerTs>(Handlers)...);
859 /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
860 /// unhandled errors (or Errors returned by handlers) are re-concatenated and
862 /// Because this function returns an error, its result must also be checked
863 /// or returned. If you intend to handle all errors use handleAllErrors
864 /// (which returns void, and will abort() on unhandled errors) instead.
865 template <typename... HandlerTs>
866 Error handleErrors(Error E, HandlerTs &&... Hs) {
868 return Error::success();
870 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
872 if (Payload->isA<ErrorList>()) {
873 ErrorList &List = static_cast<ErrorList &>(*Payload);
875 for (auto &P : List.Payloads)
878 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
882 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
885 /// Behaves the same as handleErrors, except that it requires that all
886 /// errors be handled by the given handlers. If any unhandled error remains
887 /// after the handlers have run, report_fatal_error() will be called.
888 template <typename... HandlerTs>
889 void handleAllErrors(Error E, HandlerTs &&... Handlers) {
890 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
893 /// Check that E is a non-error, then drop it.
894 /// If E is an error report_fatal_error will be called.
895 inline void handleAllErrors(Error E) {
896 cantFail(std::move(E));
899 /// Handle any errors (if present) in an Expected<T>, then try a recovery path.
901 /// If the incoming value is a success value it is returned unmodified. If it
902 /// is a failure value then it the contained error is passed to handleErrors.
903 /// If handleErrors is able to handle the error then the RecoveryPath functor
904 /// is called to supply the final result. If handleErrors is not able to
905 /// handle all errors then the unhandled errors are returned.
907 /// This utility enables the follow pattern:
910 /// enum FooStrategy { Aggressive, Conservative };
911 /// Expected<Foo> foo(FooStrategy S);
913 /// auto ResultOrErr =
916 /// []() { return foo(Conservative); },
917 /// [](AggressiveStrategyError&) {
918 /// // Implicitly conusme this - we'll recover by using a conservative
923 template <typename T, typename RecoveryFtor, typename... HandlerTs>
924 Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
925 HandlerTs &&... Handlers) {
929 if (auto Err = handleErrors(ValOrErr.takeError(),
930 std::forward<HandlerTs>(Handlers)...))
931 return std::move(Err);
933 return RecoveryPath();
936 /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
937 /// will be printed before the first one is logged. A newline will be printed
938 /// after each error.
940 /// This is useful in the base level of your program to allow clean termination
941 /// (allowing clean deallocation of resources, etc.), while reporting error
942 /// information to the user.
943 void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
945 /// Write all error messages (if any) in E to a string. The newline character
946 /// is used to separate error messages.
947 inline std::string toString(Error E) {
948 SmallVector<std::string, 2> Errors;
949 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
950 Errors.push_back(EI.message());
952 return join(Errors.begin(), Errors.end(), "\n");
955 /// Consume a Error without doing anything. This method should be used
956 /// only where an error can be considered a reasonable and expected return
959 /// Uses of this method are potentially indicative of design problems: If it's
960 /// legitimate to do nothing while processing an "error", the error-producer
961 /// might be more clearly refactored to return an Optional<T>.
962 inline void consumeError(Error Err) {
963 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
966 /// Helper for Errors used as out-parameters.
968 /// This helper is for use with the Error-as-out-parameter idiom, where an error
969 /// is passed to a function or method by reference, rather than being returned.
970 /// In such cases it is helpful to set the checked bit on entry to the function
971 /// so that the error can be written to (unchecked Errors abort on assignment)
972 /// and clear the checked bit on exit so that clients cannot accidentally forget
973 /// to check the result. This helper performs these actions automatically using
977 /// Result foo(Error &Err) {
978 /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
980 /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
984 /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
985 /// used with optional Errors (Error pointers that are allowed to be null). If
986 /// ErrorAsOutParameter took an Error reference, an instance would have to be
987 /// created inside every condition that verified that Error was non-null. By
988 /// taking an Error pointer we can just create one instance at the top of the
990 class ErrorAsOutParameter {
992 ErrorAsOutParameter(Error *Err) : Err(Err) {
993 // Raise the checked bit if Err is success.
998 ~ErrorAsOutParameter() {
999 // Clear the checked bit.
1001 *Err = Error::success();
1008 /// Helper for Expected<T>s used as out-parameters.
1010 /// See ErrorAsOutParameter.
1011 template <typename T>
1012 class ExpectedAsOutParameter {
1014 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1015 : ValOrErr(ValOrErr) {
1020 ~ExpectedAsOutParameter() {
1022 ValOrErr->setUnchecked();
1026 Expected<T> *ValOrErr;
1029 /// This class wraps a std::error_code in a Error.
1031 /// This is useful if you're writing an interface that returns a Error
1032 /// (or Expected) and you want to call code that still returns
1033 /// std::error_codes.
1034 class ECError : public ErrorInfo<ECError> {
1035 friend Error errorCodeToError(std::error_code);
1038 void setErrorCode(std::error_code EC) { this->EC = EC; }
1039 std::error_code convertToErrorCode() const override { return EC; }
1040 void log(raw_ostream &OS) const override { OS << EC.message(); }
1042 // Used by ErrorInfo::classID.
1046 ECError() = default;
1047 ECError(std::error_code EC) : EC(EC) {}
1052 /// The value returned by this function can be returned from convertToErrorCode
1053 /// for Error values where no sensible translation to std::error_code exists.
1054 /// It should only be used in this situation, and should never be used where a
1055 /// sensible conversion to std::error_code is available, as attempts to convert
1056 /// to/from this error will result in a fatal error. (i.e. it is a programmatic
1057 ///error to try to convert such a value).
1058 std::error_code inconvertibleErrorCode();
1060 /// Helper for converting an std::error_code to a Error.
1061 Error errorCodeToError(std::error_code EC);
1063 /// Helper for converting an ECError to a std::error_code.
1065 /// This method requires that Err be Error() or an ECError, otherwise it
1066 /// will trigger a call to abort().
1067 std::error_code errorToErrorCode(Error Err);
1069 /// Convert an ErrorOr<T> to an Expected<T>.
1070 template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1071 if (auto EC = EO.getError())
1072 return errorCodeToError(EC);
1073 return std::move(*EO);
1076 /// Convert an Expected<T> to an ErrorOr<T>.
1077 template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1078 if (auto Err = E.takeError())
1079 return errorToErrorCode(std::move(Err));
1080 return std::move(*E);
1083 /// This class wraps a string in an Error.
1085 /// StringError is useful in cases where the client is not expected to be able
1086 /// to consume the specific error message programmatically (for example, if the
1087 /// error message is to be presented to the user).
1088 class StringError : public ErrorInfo<StringError> {
1092 StringError(const Twine &S, std::error_code EC);
1094 void log(raw_ostream &OS) const override;
1095 std::error_code convertToErrorCode() const override;
1097 const std::string &getMessage() const { return Msg; }
1104 /// Helper for check-and-exit error handling.
1106 /// For tool use only. NOT FOR USE IN LIBRARY CODE.
1110 /// Create an error on exit helper.
1111 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1112 : Banner(std::move(Banner)),
1113 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1115 /// Set the banner string for any errors caught by operator().
1116 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1118 /// Set the exit-code mapper function.
1119 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1120 this->GetExitCode = std::move(GetExitCode);
1123 /// Check Err. If it's in a failure state log the error(s) and exit.
1124 void operator()(Error Err) const { checkError(std::move(Err)); }
1126 /// Check E. If it's in a success state then return the contained value. If
1127 /// it's in a failure state log the error(s) and exit.
1128 template <typename T> T operator()(Expected<T> &&E) const {
1129 checkError(E.takeError());
1130 return std::move(*E);
1133 /// Check E. If it's in a success state then return the contained reference. If
1134 /// it's in a failure state log the error(s) and exit.
1135 template <typename T> T& operator()(Expected<T&> &&E) const {
1136 checkError(E.takeError());
1141 void checkError(Error Err) const {
1143 int ExitCode = GetExitCode(Err);
1144 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1150 std::function<int(const Error &)> GetExitCode;
1153 } // end namespace llvm
1155 #endif // LLVM_SUPPORT_ERROR_H