1 //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an API used to report recoverable errors.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_SUPPORT_ERROR_H
15 #define LLVM_SUPPORT_ERROR_H
16
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"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstdint>
32 #include <cstdlib>
33 #include <functional>
34 #include <memory>
35 #include <new>
36 #include <string>
37 #include <system_error>
38 #include <type_traits>
39 #include <utility>
40 #include <vector>
41
42 namespace llvm {
43
44 class ErrorSuccess;
45
46 /// Base class for error info classes. Do not extend this directly: Extend
47 /// the ErrorInfo template subclass instead.
48 class ErrorInfoBase {
49 public:
50 virtual ~ErrorInfoBase() = default;
51
52 /// Print an error message to an output stream.
53 virtual void log(raw_ostream &OS) const = 0;
54
55 /// Return the error message as a string.
message()56 virtual std::string message() const {
57 std::string Msg;
58 raw_string_ostream OS(Msg);
59 log(OS);
60 return OS.str();
61 }
62
63 /// Convert this error to a std::error_code.
64 ///
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;
68
69 // Returns the class ID for this type.
classID()70 static const void *classID() { return &ID; }
71
72 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
73 virtual const void *dynamicClassID() const = 0;
74
75 // Check whether this instance is a subclass of the class identified by
76 // ClassID.
isA(const void * const ClassID)77 virtual bool isA(const void *const ClassID) const {
78 return ClassID == classID();
79 }
80
81 // Check whether this instance is a subclass of ErrorInfoT.
isA()82 template <typename ErrorInfoT> bool isA() const {
83 return isA(ErrorInfoT::classID());
84 }
85
86 private:
87 virtual void anchor();
88
89 static char ID;
90 };
91
92 /// Lightweight error class with error context and mandatory checking.
93 ///
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.
98 ///
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.
103 ///
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.:
107 ///
108 /// @code{.cpp}
109 /// Error foo(<...>);
110 ///
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
114 /// // destroyed.
115 /// @endcode
116 ///
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
119 /// returns success.
120 ///
121 /// For Error instances representing failure, you must use either the
122 /// handleErrors or handleAllErrors function with a typed handler. E.g.:
123 ///
124 /// @code{.cpp}
125 /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
126 /// // Custom error info.
127 /// };
128 ///
129 /// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
130 ///
131 /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
132 /// auto NewE =
133 /// handleErrors(E,
134 /// [](const MyErrorInfo &M) {
135 /// // Deal with the error.
136 /// },
137 /// [](std::unique_ptr<OtherError> M) -> Error {
138 /// if (canHandle(*M)) {
139 /// // handle error.
140 /// return Error::success();
141 /// }
142 /// // Couldn't handle this error instance. Pass it up the stack.
143 /// return Error(std::move(M));
144 /// );
145 /// // Note - we must check or return NewE in case any of the handlers
146 /// // returned a new error.
147 /// @endcode
148 ///
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.
153 ///
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;
161
162 // handleErrors needs to be able to set the Checked flag.
163 template <typename... HandlerTs>
164 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
165
166 // Expected<T> needs to be able to steal the payload when constructed from an
167 // error.
168 template <typename T> friend class Expected;
169
170 protected:
171 /// Create a success value. Prefer using 'Error::success()' for readability
Error()172 Error() {
173 setPtr(nullptr);
174 setChecked(false);
175 }
176
177 public:
178 /// Create a success value.
179 static ErrorSuccess success();
180
181 // Errors are not copy-constructable.
182 Error(const Error &Other) = delete;
183
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.
Error(Error && Other)187 Error(Error &&Other) {
188 setChecked(true);
189 *this = std::move(Other);
190 }
191
192 /// Create an error value. Prefer using the 'make_error' function, but
193 /// this constructor can be useful when "re-throwing" errors from handlers.
Error(std::unique_ptr<ErrorInfoBase> Payload)194 Error(std::unique_ptr<ErrorInfoBase> Payload) {
195 setPtr(Payload.release());
196 setChecked(false);
197 }
198
199 // Errors are not copy-assignable.
200 Error &operator=(const Error &Other) = delete;
201
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.
208 assertIsChecked();
209 setPtr(Other.getPtr());
210
211 // This Error is unchecked, even if the source error was checked.
212 setChecked(false);
213
214 // Null out Other's payload and set its checked bit.
215 Other.setPtr(nullptr);
216 Other.setChecked(true);
217
218 return *this;
219 }
220
221 /// Destroy a Error. Fails with a call to abort() if the error is
222 /// unchecked.
~Error()223 ~Error() {
224 assertIsChecked();
225 delete getPtr();
226 }
227
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;
234 }
235
236 /// Check whether one error is a subclass of another.
isA()237 template <typename ErrT> bool isA() const {
238 return getPtr() && getPtr()->isA(ErrT::classID());
239 }
240
241 /// Returns the dynamic class id of this error, or null if this is a success
242 /// value.
dynamicClassID()243 const void* dynamicClassID() const {
244 if (!getPtr())
245 return nullptr;
246 return getPtr()->dynamicClassID();
247 }
248
249 private:
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
255 // inlined.
256 LLVM_ATTRIBUTE_NORETURN
257 void fatalUncheckedError() const;
258 #endif
259
assertIsChecked()260 void assertIsChecked() {
261 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
262 if (LLVM_UNLIKELY(!getChecked() || getPtr()))
263 fatalUncheckedError();
264 #endif
265 }
266
getPtr()267 ErrorInfoBase *getPtr() const {
268 return reinterpret_cast<ErrorInfoBase*>(
269 reinterpret_cast<uintptr_t>(Payload) &
270 ~static_cast<uintptr_t>(0x1));
271 }
272
setPtr(ErrorInfoBase * EI)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));
279 #else
280 Payload = EI;
281 #endif
282 }
283
getChecked()284 bool getChecked() const {
285 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
286 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
287 #else
288 return true;
289 #endif
290 }
291
setChecked(bool V)292 void setChecked(bool V) {
293 Payload = reinterpret_cast<ErrorInfoBase*>(
294 (reinterpret_cast<uintptr_t>(Payload) &
295 ~static_cast<uintptr_t>(0x1)) |
296 (V ? 0 : 1));
297 }
298
takePayload()299 std::unique_ptr<ErrorInfoBase> takePayload() {
300 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
301 setPtr(nullptr);
302 setChecked(true);
303 return Tmp;
304 }
305
306 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
307 if (auto P = E.getPtr())
308 P->log(OS);
309 else
310 OS << "success";
311 return OS;
312 }
313
314 ErrorInfoBase *Payload = nullptr;
315 };
316
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
319 /// compile time.
320 class ErrorSuccess : public Error {};
321
success()322 inline ErrorSuccess Error::success() { return ErrorSuccess(); }
323
324 /// Make a Error instance representing failure using the given error info
325 /// type.
make_error(ArgTs &&...Args)326 template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
327 return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
328 }
329
330 /// Base class for user error types. Users should declare their error types
331 /// like:
332 ///
333 /// class MyError : public ErrorInfo<MyError> {
334 /// ....
335 /// };
336 ///
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 {
341 public:
classID()342 static const void *classID() { return &ThisErrT::ID; }
343
dynamicClassID()344 const void *dynamicClassID() const override { return &ThisErrT::ID; }
345
isA(const void * const ClassID)346 bool isA(const void *const ClassID) const override {
347 return ClassID == classID() || ParentErrT::isA(ClassID);
348 }
349 };
350
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
355 // ErrorList.
356 template <typename... HandlerTs>
357 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
358
359 // joinErrors is implemented in terms of join.
360 friend Error joinErrors(Error, Error);
361
362 public:
log(raw_ostream & OS)363 void log(raw_ostream &OS) const override {
364 OS << "Multiple errors:\n";
365 for (auto &ErrPayload : Payloads) {
366 ErrPayload->log(OS);
367 OS << "\n";
368 }
369 }
370
371 std::error_code convertToErrorCode() const override;
372
373 // Used by ErrorInfo::classID.
374 static char ID;
375
376 private:
ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,std::unique_ptr<ErrorInfoBase> Payload2)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));
383 }
384
join(Error E1,Error E2)385 static Error join(Error E1, Error E2) {
386 if (!E1)
387 return E2;
388 if (!E2)
389 return E1;
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));
397 } else
398 E1List.Payloads.push_back(E2.takePayload());
399
400 return E1;
401 }
402 if (E2.isA<ErrorList>()) {
403 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
404 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
405 return E2;
406 }
407 return Error(std::unique_ptr<ErrorList>(
408 new ErrorList(E1.takePayload(), E2.takePayload())));
409 }
410
411 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
412 };
413
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.
joinErrors(Error E1,Error E2)417 inline Error joinErrors(Error E1, Error E2) {
418 return ErrorList::join(std::move(E1), std::move(E2));
419 }
420
421 /// Tagged union holding either a T or a Error.
422 ///
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;
430
431 static const bool isRef = std::is_reference<T>::value;
432
433 using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
434
435 using error_type = std::unique_ptr<ErrorInfoBase>;
436
437 public:
438 using storage_type = typename std::conditional<isRef, wrap, T>::type;
439 using value_type = T;
440
441 private:
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 *;
446
447 public:
448 /// Create an Expected<T> error value from the given Error.
Expected(Error Err)449 Expected(Error Err)
450 : HasError(true)
451 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
452 // Expected is unchecked upon construction in Debug builds.
453 , Unchecked(true)
454 #endif
455 {
456 assert(Err && "Cannot create Expected<T> from Error success value.");
457 new (getErrorStorage()) error_type(Err.takePayload());
458 }
459
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;
464
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
470 * = nullptr)
HasError(false)471 : HasError(false)
472 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
473 // Expected is unchecked upon construction in Debug builds.
474 , Unchecked(true)
475 #endif
476 {
477 new (getStorage()) storage_type(std::forward<OtherT>(Val));
478 }
479
480 /// Move construct an Expected<T> value.
Expected(Expected && Other)481 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
482
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
488 * = nullptr) {
489 moveConstruct(std::move(Other));
490 }
491
492 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
493 /// isn't convertible to T.
494 template <class OtherT>
495 explicit Expected(
496 Expected<OtherT> &&Other,
497 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
498 nullptr) {
499 moveConstruct(std::move(Other));
500 }
501
502 /// Move-assign from another Expected<T>.
503 Expected &operator=(Expected &&Other) {
504 moveAssign(std::move(Other));
505 return *this;
506 }
507
508 /// Destroy an Expected<T>.
~Expected()509 ~Expected() {
510 assertIsChecked();
511 if (!HasError)
512 getStorage()->~storage_type();
513 else
514 getErrorStorage()->~error_type();
515 }
516
517 /// Return false if there is an error.
518 explicit operator bool() {
519 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
520 Unchecked = HasError;
521 #endif
522 return !HasError;
523 }
524
525 /// Returns a reference to the stored T value.
get()526 reference get() {
527 assertIsChecked();
528 return *getStorage();
529 }
530
531 /// Returns a const reference to the stored T value.
get()532 const_reference get() const {
533 assertIsChecked();
534 return const_cast<Expected<T> *>(this)->get();
535 }
536
537 /// Check that this Expected<T> is an error of type ErrT.
errorIsA()538 template <typename ErrT> bool errorIsA() const {
539 return HasError && (*getErrorStorage())->template isA<ErrT>();
540 }
541
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.
takeError()546 Error takeError() {
547 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
548 Unchecked = false;
549 #endif
550 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
551 }
552
553 /// Returns a pointer to the stored T value.
554 pointer operator->() {
555 assertIsChecked();
556 return toPointer(getStorage());
557 }
558
559 /// Returns a const pointer to the stored T value.
560 const_pointer operator->() const {
561 assertIsChecked();
562 return toPointer(getStorage());
563 }
564
565 /// Returns a reference to the stored T value.
566 reference operator*() {
567 assertIsChecked();
568 return *getStorage();
569 }
570
571 /// Returns a const reference to the stored T value.
572 const_reference operator*() const {
573 assertIsChecked();
574 return *getStorage();
575 }
576
577 private:
578 template <class T1>
compareThisIfSameType(const T1 & a,const T1 & b)579 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
580 return &a == &b;
581 }
582
583 template <class T1, class T2>
compareThisIfSameType(const T1 & a,const T2 & b)584 static bool compareThisIfSameType(const T1 &a, const T2 &b) {
585 return false;
586 }
587
moveConstruct(Expected<OtherT> && Other)588 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
589 HasError = Other.HasError;
590 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
591 Unchecked = true;
592 Other.Unchecked = false;
593 #endif
594
595 if (!HasError)
596 new (getStorage()) storage_type(std::move(*Other.getStorage()));
597 else
598 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
599 }
600
moveAssign(Expected<OtherT> && Other)601 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
602 assertIsChecked();
603
604 if (compareThisIfSameType(*this, Other))
605 return;
606
607 this->~Expected();
608 new (this) Expected(std::move(Other));
609 }
610
toPointer(pointer Val)611 pointer toPointer(pointer Val) { return Val; }
612
toPointer(const_pointer Val)613 const_pointer toPointer(const_pointer Val) const { return Val; }
614
toPointer(wrap * Val)615 pointer toPointer(wrap *Val) { return &Val->get(); }
616
toPointer(const wrap * Val)617 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
618
getStorage()619 storage_type *getStorage() {
620 assert(!HasError && "Cannot get value when an error exists!");
621 return reinterpret_cast<storage_type *>(TStorage.buffer);
622 }
623
getStorage()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);
627 }
628
getErrorStorage()629 error_type *getErrorStorage() {
630 assert(HasError && "Cannot get error when a value exists!");
631 return reinterpret_cast<error_type *>(ErrorStorage.buffer);
632 }
633
getErrorStorage()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);
637 }
638
639 // Used by ExpectedAsOutParameter to reset the checked flag.
setUnchecked()640 void setUnchecked() {
641 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
642 Unchecked = true;
643 #endif
644 }
645
646 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
647 LLVM_ATTRIBUTE_NORETURN
648 LLVM_ATTRIBUTE_NOINLINE
fatalUncheckedExpected()649 void fatalUncheckedExpected() const {
650 dbgs() << "Expected<T> must be checked before access or destruction.\n";
651 if (HasError) {
652 dbgs() << "Unchecked Expected<T> contained error:\n";
653 (*getErrorStorage())->log(dbgs());
654 } else
655 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
656 "values in success mode must still be checked prior to being "
657 "destroyed).\n";
658 abort();
659 }
660 #endif
661
assertIsChecked()662 void assertIsChecked() {
663 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
664 if (LLVM_UNLIKELY(Unchecked))
665 fatalUncheckedExpected();
666 #endif
667 }
668
669 union {
670 AlignedCharArrayUnion<storage_type> TStorage;
671 AlignedCharArrayUnion<error_type> ErrorStorage;
672 };
673 bool HasError : 1;
674 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
675 bool Unchecked : 1;
676 #endif
677 };
678
679 /// Report a serious error, calling any installed error handler. See
680 /// ErrorHandling.h.
681 LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err,
682 bool gen_crash_diag = true);
683
684 /// Report a fatal error if Err is a failure value.
685 ///
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.
688 ///
689 /// @code{.cpp}
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);
694 ///
695 /// cantFail(foo(false));
696 /// @endcode
697 inline void cantFail(Error Err, const char *Msg = nullptr) {
698 if (Err) {
699 if (!Msg)
700 Msg = "Failure value returned from cantFail wrapped call";
701 llvm_unreachable(Msg);
702 }
703 }
704
705 /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
706 /// returns the contained value.
707 ///
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.
710 ///
711 /// @code{.cpp}
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);
715 ///
716 /// int X = cantFail(foo(false));
717 /// @endcode
718 template <typename T>
719 T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
720 if (ValOrErr)
721 return std::move(*ValOrErr);
722 else {
723 if (!Msg)
724 Msg = "Failure value returned from cantFail wrapped call";
725 llvm_unreachable(Msg);
726 }
727 }
728
729 /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
730 /// returns the contained reference.
731 ///
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.
734 ///
735 /// @code{.cpp}
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);
739 ///
740 /// Bar &X = cantFail(foo(false));
741 /// @endcode
742 template <typename T>
743 T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
744 if (ValOrErr)
745 return *ValOrErr;
746 else {
747 if (!Msg)
748 Msg = "Failure value returned from cantFail wrapped call";
749 llvm_unreachable(Msg);
750 }
751 }
752
753 /// Helper for testing applicability of, and applying, handlers for
754 /// ErrorInfo types.
755 template <typename HandlerT>
756 class ErrorHandlerTraits
757 : public ErrorHandlerTraits<decltype(
758 &std::remove_reference<HandlerT>::type::operator())> {};
759
760 // Specialization functions of the form 'Error (const ErrT&)'.
761 template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
762 public:
appliesTo(const ErrorInfoBase & E)763 static bool appliesTo(const ErrorInfoBase &E) {
764 return E.template isA<ErrT>();
765 }
766
767 template <typename HandlerT>
apply(HandlerT && H,std::unique_ptr<ErrorInfoBase> E)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));
771 }
772 };
773
774 // Specialization functions of the form 'void (const ErrT&)'.
775 template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
776 public:
appliesTo(const ErrorInfoBase & E)777 static bool appliesTo(const ErrorInfoBase &E) {
778 return E.template isA<ErrT>();
779 }
780
781 template <typename HandlerT>
apply(HandlerT && H,std::unique_ptr<ErrorInfoBase> E)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();
786 }
787 };
788
789 /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
790 template <typename ErrT>
791 class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
792 public:
appliesTo(const ErrorInfoBase & E)793 static bool appliesTo(const ErrorInfoBase &E) {
794 return E.template isA<ErrT>();
795 }
796
797 template <typename HandlerT>
apply(HandlerT && H,std::unique_ptr<ErrorInfoBase> E)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));
802 }
803 };
804
805 /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
806 template <typename ErrT>
807 class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
808 public:
appliesTo(const ErrorInfoBase & E)809 static bool appliesTo(const ErrorInfoBase &E) {
810 return E.template isA<ErrT>();
811 }
812
813 template <typename HandlerT>
apply(HandlerT && H,std::unique_ptr<ErrorInfoBase> E)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()));
817 H(std::move(SubE));
818 return Error::success();
819 }
820 };
821
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 &)> {};
826
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 &)> {};
831
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 &)> {};
836
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 &)> {};
841
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>)> {};
847
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>)> {};
853
handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload)854 inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
855 return Error(std::move(Payload));
856 }
857
858 template <typename HandlerT, typename... HandlerTs>
handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,HandlerT && Handler,HandlerTs &&...Handlers)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),
863 std::move(Payload));
864 return handleErrorImpl(std::move(Payload),
865 std::forward<HandlerTs>(Handlers)...);
866 }
867
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
870 /// returned.
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>
handleErrors(Error E,HandlerTs &&...Hs)875 Error handleErrors(Error E, HandlerTs &&... Hs) {
876 if (!E)
877 return Error::success();
878
879 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
880
881 if (Payload->isA<ErrorList>()) {
882 ErrorList &List = static_cast<ErrorList &>(*Payload);
883 Error R;
884 for (auto &P : List.Payloads)
885 R = ErrorList::join(
886 std::move(R),
887 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
888 return R;
889 }
890
891 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
892 }
893
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>
handleAllErrors(Error E,HandlerTs &&...Handlers)898 void handleAllErrors(Error E, HandlerTs &&... Handlers) {
899 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
900 }
901
902 /// Check that E is a non-error, then drop it.
903 /// If E is an error, llvm_unreachable will be called.
handleAllErrors(Error E)904 inline void handleAllErrors(Error E) {
905 cantFail(std::move(E));
906 }
907
908 /// Handle any errors (if present) in an Expected<T>, then try a recovery path.
909 ///
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.
915 ///
916 /// This utility enables the follow pattern:
917 ///
918 /// @code{.cpp}
919 /// enum FooStrategy { Aggressive, Conservative };
920 /// Expected<Foo> foo(FooStrategy S);
921 ///
922 /// auto ResultOrErr =
923 /// handleExpected(
924 /// foo(Aggressive),
925 /// []() { return foo(Conservative); },
926 /// [](AggressiveStrategyError&) {
927 /// // Implicitly conusme this - we'll recover by using a conservative
928 /// // strategy.
929 /// });
930 ///
931 /// @endcode
932 template <typename T, typename RecoveryFtor, typename... HandlerTs>
handleExpected(Expected<T> ValOrErr,RecoveryFtor && RecoveryPath,HandlerTs &&...Handlers)933 Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
934 HandlerTs &&... Handlers) {
935 if (ValOrErr)
936 return ValOrErr;
937
938 if (auto Err = handleErrors(ValOrErr.takeError(),
939 std::forward<HandlerTs>(Handlers)...))
940 return std::move(Err);
941
942 return RecoveryPath();
943 }
944
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.
948 ///
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);
953
954 /// Write all error messages (if any) in E to a string. The newline character
955 /// is used to separate error messages.
toString(Error E)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());
960 });
961 return join(Errors.begin(), Errors.end(), "\n");
962 }
963
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
966 /// value.
967 ///
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>.
consumeError(Error Err)971 inline void consumeError(Error Err) {
972 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
973 }
974
975 /// Helper for converting an Error to a bool.
976 ///
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).
errorToBool(Error Err)980 inline bool errorToBool(Error Err) {
981 bool IsError = static_cast<bool>(Err);
982 if (IsError)
983 consumeError(std::move(Err));
984 return IsError;
985 }
986
987 /// Helper for Errors used as out-parameters.
988 ///
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
995 /// RAII:
996 ///
997 /// @code{.cpp}
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.
1002 /// }
1003 /// @endcode
1004 ///
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
1010 /// function.
1011 class ErrorAsOutParameter {
1012 public:
ErrorAsOutParameter(Error * Err)1013 ErrorAsOutParameter(Error *Err) : Err(Err) {
1014 // Raise the checked bit if Err is success.
1015 if (Err)
1016 (void)!!*Err;
1017 }
1018
~ErrorAsOutParameter()1019 ~ErrorAsOutParameter() {
1020 // Clear the checked bit.
1021 if (Err && !*Err)
1022 *Err = Error::success();
1023 }
1024
1025 private:
1026 Error *Err;
1027 };
1028
1029 /// Helper for Expected<T>s used as out-parameters.
1030 ///
1031 /// See ErrorAsOutParameter.
1032 template <typename T>
1033 class ExpectedAsOutParameter {
1034 public:
ExpectedAsOutParameter(Expected<T> * ValOrErr)1035 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1036 : ValOrErr(ValOrErr) {
1037 if (ValOrErr)
1038 (void)!!*ValOrErr;
1039 }
1040
~ExpectedAsOutParameter()1041 ~ExpectedAsOutParameter() {
1042 if (ValOrErr)
1043 ValOrErr->setUnchecked();
1044 }
1045
1046 private:
1047 Expected<T> *ValOrErr;
1048 };
1049
1050 /// This class wraps a std::error_code in a Error.
1051 ///
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);
1057
1058 public:
setErrorCode(std::error_code EC)1059 void setErrorCode(std::error_code EC) { this->EC = EC; }
convertToErrorCode()1060 std::error_code convertToErrorCode() const override { return EC; }
log(raw_ostream & OS)1061 void log(raw_ostream &OS) const override { OS << EC.message(); }
1062
1063 // Used by ErrorInfo::classID.
1064 static char ID;
1065
1066 protected:
1067 ECError() = default;
ECError(std::error_code EC)1068 ECError(std::error_code EC) : EC(EC) {}
1069
1070 std::error_code EC;
1071 };
1072
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();
1080
1081 /// Helper for converting an std::error_code to a Error.
1082 Error errorCodeToError(std::error_code EC);
1083
1084 /// Helper for converting an ECError to a std::error_code.
1085 ///
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);
1089
1090 /// Convert an ErrorOr<T> to an Expected<T>.
errorOrToExpected(ErrorOr<T> && EO)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);
1095 }
1096
1097 /// Convert an Expected<T> to an ErrorOr<T>.
expectedToErrorOr(Expected<T> && E)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);
1102 }
1103
1104 /// This class wraps a string in an Error.
1105 ///
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> {
1110 public:
1111 static char ID;
1112
1113 StringError(const Twine &S, std::error_code EC);
1114
1115 void log(raw_ostream &OS) const override;
1116 std::error_code convertToErrorCode() const override;
1117
getMessage()1118 const std::string &getMessage() const { return Msg; }
1119
1120 private:
1121 std::string Msg;
1122 std::error_code EC;
1123 };
1124
1125 /// Create formatted StringError object.
1126 template <typename... Ts>
createStringError(std::error_code EC,char const * Fmt,const Ts &...Vals)1127 Error createStringError(std::error_code EC, char const *Fmt,
1128 const Ts &... Vals) {
1129 std::string Buffer;
1130 raw_string_ostream Stream(Buffer);
1131 Stream << format(Fmt, Vals...);
1132 return make_error<StringError>(Stream.str(), EC);
1133 }
1134
1135 Error createStringError(std::error_code EC, char const *Msg);
1136
1137 /// Helper for check-and-exit error handling.
1138 ///
1139 /// For tool use only. NOT FOR USE IN LIBRARY CODE.
1140 ///
1141 class ExitOnError {
1142 public:
1143 /// Create an error on exit helper.
1144 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
Banner(std::move (Banner))1145 : Banner(std::move(Banner)),
1146 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1147
1148 /// Set the banner string for any errors caught by operator().
setBanner(std::string Banner)1149 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1150
1151 /// Set the exit-code mapper function.
setExitCodeMapper(std::function<int (const Error &)> GetExitCode)1152 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1153 this->GetExitCode = std::move(GetExitCode);
1154 }
1155
1156 /// Check Err. If it's in a failure state log the error(s) and exit.
operator()1157 void operator()(Error Err) const { checkError(std::move(Err)); }
1158
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.
operator()1161 template <typename T> T operator()(Expected<T> &&E) const {
1162 checkError(E.takeError());
1163 return std::move(*E);
1164 }
1165
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.
operator()1168 template <typename T> T& operator()(Expected<T&> &&E) const {
1169 checkError(E.takeError());
1170 return *E;
1171 }
1172
1173 private:
checkError(Error Err)1174 void checkError(Error Err) const {
1175 if (Err) {
1176 int ExitCode = GetExitCode(Err);
1177 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1178 exit(ExitCode);
1179 }
1180 }
1181
1182 std::string Banner;
1183 std::function<int(const Error &)> GetExitCode;
1184 };
1185
1186 } // end namespace llvm
1187
1188 #endif // LLVM_SUPPORT_ERROR_H
1189