1 //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines an API used to report recoverable errors.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_SUPPORT_ERROR_H
14 #define LLVM_SUPPORT_ERROR_H
15
16 #include "llvm-c/Error.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Config/abi-breaking.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/ErrorOr.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <cassert>
26 #include <cstdint>
27 #include <cstdlib>
28 #include <functional>
29 #include <memory>
30 #include <new>
31 #include <optional>
32 #include <string>
33 #include <system_error>
34 #include <type_traits>
35 #include <utility>
36 #include <vector>
37
38 namespace llvm {
39
40 class ErrorSuccess;
41
42 /// Base class for error info classes. Do not extend this directly: Extend
43 /// the ErrorInfo template subclass instead.
44 class LLVM_ABI ErrorInfoBase {
45 public:
46 virtual ~ErrorInfoBase() = default;
47
48 /// Print an error message to an output stream.
49 virtual void log(raw_ostream &OS) const = 0;
50
51 /// Return the error message as a string.
message()52 virtual std::string message() const {
53 std::string Msg;
54 raw_string_ostream OS(Msg);
55 log(OS);
56 return Msg;
57 }
58
59 /// Convert this error to a std::error_code.
60 ///
61 /// This is a temporary crutch to enable interaction with code still
62 /// using std::error_code. It will be removed in the future.
63 virtual std::error_code convertToErrorCode() const = 0;
64
65 // Returns the class ID for this type.
classID()66 static const void *classID() { return &ID; }
67
68 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
69 virtual const void *dynamicClassID() const = 0;
70
71 // Check whether this instance is a subclass of the class identified by
72 // ClassID.
isA(const void * const ClassID)73 virtual bool isA(const void *const ClassID) const {
74 return ClassID == classID();
75 }
76
77 // Check whether this instance is a subclass of ErrorInfoT.
isA()78 template <typename ErrorInfoT> bool isA() const {
79 return isA(ErrorInfoT::classID());
80 }
81
82 private:
83 virtual void anchor();
84
85 static char ID;
86 };
87
88 /// Lightweight error class with error context and mandatory checking.
89 ///
90 /// Instances of this class wrap a ErrorInfoBase pointer. Failure states
91 /// are represented by setting the pointer to a ErrorInfoBase subclass
92 /// instance containing information describing the failure. Success is
93 /// represented by a null pointer value.
94 ///
95 /// Instances of Error also contains a 'Checked' flag, which must be set
96 /// before the destructor is called, otherwise the destructor will trigger a
97 /// runtime error. This enforces at runtime the requirement that all Error
98 /// instances be checked or returned to the caller.
99 ///
100 /// There are two ways to set the checked flag, depending on what state the
101 /// Error instance is in. For Error instances indicating success, it
102 /// is sufficient to invoke the boolean conversion operator. E.g.:
103 ///
104 /// @code{.cpp}
105 /// Error foo(<...>);
106 ///
107 /// if (auto E = foo(<...>))
108 /// return E; // <- Return E if it is in the error state.
109 /// // We have verified that E was in the success state. It can now be safely
110 /// // destroyed.
111 /// @endcode
112 ///
113 /// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
114 /// without testing the return value will raise a runtime error, even if foo
115 /// returns success.
116 ///
117 /// For Error instances representing failure, you must use either the
118 /// handleErrors or handleAllErrors function with a typed handler. E.g.:
119 ///
120 /// @code{.cpp}
121 /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
122 /// // Custom error info.
123 /// };
124 ///
125 /// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
126 ///
127 /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
128 /// auto NewE =
129 /// handleErrors(std::move(E),
130 /// [](const MyErrorInfo &M) {
131 /// // Deal with the error.
132 /// },
133 /// [](std::unique_ptr<OtherError> M) -> Error {
134 /// if (canHandle(*M)) {
135 /// // handle error.
136 /// return Error::success();
137 /// }
138 /// // Couldn't handle this error instance. Pass it up the stack.
139 /// return Error(std::move(M));
140 /// });
141 /// // Note - The error passed to handleErrors will be marked as checked. If
142 /// // there is no matched handler, a new error with the same payload is
143 /// // created and returned.
144 /// // The handlers take the error checked by handleErrors as an argument,
145 /// // which can be used to retrieve more information. If a new error is
146 /// // created by a handler, it will be passed back to the caller of
147 /// // handleErrors and needs to be checked or return up to the stack.
148 /// // Otherwise, the passed-in error is considered consumed.
149 /// @endcode
150 ///
151 /// The handleAllErrors function is identical to handleErrors, except
152 /// that it has a void return type, and requires all errors to be handled and
153 /// no new errors be returned. It prevents errors (assuming they can all be
154 /// handled) from having to be bubbled all the way to the top-level.
155 ///
156 /// *All* Error instances must be checked before destruction, even if
157 /// they're moved-assigned or constructed from Success values that have already
158 /// been checked. This enforces checking through all levels of the call stack.
159 class [[nodiscard]] Error {
160 // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors
161 // to add to the error list. It can't rely on handleErrors for this, since
162 // handleErrors does not support ErrorList handlers.
163 friend class ErrorList;
164
165 // handleErrors needs to be able to set the Checked flag.
166 template <typename... HandlerTs>
167 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
168 // visitErrors needs direct access to the payload.
169 template <typename HandlerT>
170 friend void visitErrors(const Error &E, HandlerT H);
171
172 // Expected<T> needs to be able to steal the payload when constructed from an
173 // error.
174 template <typename T> friend class Expected;
175
176 // wrap needs to be able to steal the payload.
177 friend LLVMErrorRef wrap(Error);
178
179 protected:
180 /// Create a success value. Prefer using 'Error::success()' for readability
Error()181 Error() {
182 setPtr(nullptr);
183 setChecked(false);
184 }
185
186 public:
187 /// Create a success value.
188 static ErrorSuccess success();
189
190 // Errors are not copy-constructable.
191 Error(const Error &Other) = delete;
192
193 /// Move-construct an error value. The newly constructed error is considered
194 /// unchecked, even if the source error had been checked. The original error
195 /// becomes a checked Success value, regardless of its original state.
Error(Error && Other)196 Error(Error &&Other) {
197 setChecked(true);
198 *this = std::move(Other);
199 }
200
201 /// Create an error value. Prefer using the 'make_error' function, but
202 /// this constructor can be useful when "re-throwing" errors from handlers.
Error(std::unique_ptr<ErrorInfoBase> Payload)203 Error(std::unique_ptr<ErrorInfoBase> Payload) {
204 setPtr(Payload.release());
205 setChecked(false);
206 }
207
208 // Errors are not copy-assignable.
209 Error &operator=(const Error &Other) = delete;
210
211 /// Move-assign an error value. The current error must represent success, you
212 /// you cannot overwrite an unhandled error. The current error is then
213 /// considered unchecked. The source error becomes a checked success value,
214 /// regardless of its original state.
215 Error &operator=(Error &&Other) {
216 // Don't allow overwriting of unchecked values.
217 assertIsChecked();
218 setPtr(Other.getPtr());
219
220 // This Error is unchecked, even if the source error was checked.
221 setChecked(false);
222
223 // Null out Other's payload and set its checked bit.
224 Other.setPtr(nullptr);
225 Other.setChecked(true);
226
227 return *this;
228 }
229
230 /// Destroy a Error. Fails with a call to abort() if the error is
231 /// unchecked.
~Error()232 ~Error() {
233 assertIsChecked();
234 delete getPtr();
235 }
236
237 /// Bool conversion. Returns true if this Error is in a failure state,
238 /// and false if it is in an accept state. If the error is in a Success state
239 /// it will be considered checked.
240 explicit operator bool() {
241 setChecked(getPtr() == nullptr);
242 return getPtr() != nullptr;
243 }
244
245 /// Check whether one error is a subclass of another.
isA()246 template <typename ErrT> bool isA() const {
247 return getPtr() && getPtr()->isA(ErrT::classID());
248 }
249
250 /// Returns the dynamic class id of this error, or null if this is a success
251 /// value.
dynamicClassID()252 const void* dynamicClassID() const {
253 if (!getPtr())
254 return nullptr;
255 return getPtr()->dynamicClassID();
256 }
257
258 private:
259 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
260 // assertIsChecked() happens very frequently, but under normal circumstances
261 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
262 // of debug prints can cause the function to be too large for inlining. So
263 // it's important that we define this function out of line so that it can't be
264 // inlined.
265 [[noreturn]] LLVM_ABI void fatalUncheckedError() const;
266 #endif
267
assertIsChecked()268 void assertIsChecked() {
269 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
270 if (LLVM_UNLIKELY(!getChecked() || getPtr()))
271 fatalUncheckedError();
272 #endif
273 }
274
getPtr()275 ErrorInfoBase *getPtr() const {
276 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
277 return reinterpret_cast<ErrorInfoBase*>(
278 reinterpret_cast<uintptr_t>(Payload) &
279 ~static_cast<uintptr_t>(0x1));
280 #else
281 return Payload;
282 #endif
283 }
284
setPtr(ErrorInfoBase * EI)285 void setPtr(ErrorInfoBase *EI) {
286 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
287 Payload = reinterpret_cast<ErrorInfoBase*>(
288 (reinterpret_cast<uintptr_t>(EI) &
289 ~static_cast<uintptr_t>(0x1)) |
290 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
291 #else
292 Payload = EI;
293 #endif
294 }
295
getChecked()296 bool getChecked() const {
297 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
298 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
299 #else
300 return true;
301 #endif
302 }
303
setChecked(bool V)304 void setChecked(bool V) {
305 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
306 Payload = reinterpret_cast<ErrorInfoBase*>(
307 (reinterpret_cast<uintptr_t>(Payload) &
308 ~static_cast<uintptr_t>(0x1)) |
309 (V ? 0 : 1));
310 #endif
311 }
312
takePayload()313 std::unique_ptr<ErrorInfoBase> takePayload() {
314 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
315 setPtr(nullptr);
316 setChecked(true);
317 return Tmp;
318 }
319
320 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
321 if (auto *P = E.getPtr())
322 P->log(OS);
323 else
324 OS << "success";
325 return OS;
326 }
327
328 ErrorInfoBase *Payload = nullptr;
329 };
330
331 /// Subclass of Error for the sole purpose of identifying the success path in
332 /// the type system. This allows to catch invalid conversion to Expected<T> at
333 /// compile time.
334 class ErrorSuccess final : public Error {};
335
success()336 inline ErrorSuccess Error::success() { return ErrorSuccess(); }
337
338 /// Make a Error instance representing failure using the given error info
339 /// type.
make_error(ArgTs &&...Args)340 template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
341 return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
342 }
343
344 /// Base class for user error types. Users should declare their error types
345 /// like:
346 ///
347 /// class MyError : public ErrorInfo<MyError> {
348 /// ....
349 /// };
350 ///
351 /// This class provides an implementation of the ErrorInfoBase::kind
352 /// method, which is used by the Error RTTI system.
353 template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
354 class ErrorInfo : public ParentErrT {
355 public:
356 using ParentErrT::ParentErrT; // inherit constructors
357
classID()358 static const void *classID() { return &ThisErrT::ID; }
359
dynamicClassID()360 const void *dynamicClassID() const override { return &ThisErrT::ID; }
361
isA(const void * const ClassID)362 bool isA(const void *const ClassID) const override {
363 return ClassID == classID() || ParentErrT::isA(ClassID);
364 }
365 };
366
367 /// Special ErrorInfo subclass representing a list of ErrorInfos.
368 /// Instances of this class are constructed by joinError.
369 class LLVM_ABI ErrorList final : public ErrorInfo<ErrorList> {
370 // handleErrors needs to be able to iterate the payload list of an
371 // ErrorList.
372 template <typename... HandlerTs>
373 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
374 // visitErrors needs to be able to iterate the payload list of an
375 // ErrorList.
376 template <typename HandlerT>
377 friend void visitErrors(const Error &E, HandlerT H);
378
379 // joinErrors is implemented in terms of join.
380 friend Error joinErrors(Error, Error);
381
382 public:
log(raw_ostream & OS)383 void log(raw_ostream &OS) const override {
384 OS << "Multiple errors:\n";
385 for (const auto &ErrPayload : Payloads) {
386 ErrPayload->log(OS);
387 OS << "\n";
388 }
389 }
390
391 std::error_code convertToErrorCode() const override;
392
393 // Used by ErrorInfo::classID.
394 static char ID;
395
396 private:
ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,std::unique_ptr<ErrorInfoBase> Payload2)397 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
398 std::unique_ptr<ErrorInfoBase> Payload2) {
399 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
400 "ErrorList constructor payloads should be singleton errors");
401 Payloads.push_back(std::move(Payload1));
402 Payloads.push_back(std::move(Payload2));
403 }
404
405 // Explicitly non-copyable.
406 ErrorList(ErrorList const &) = delete;
407 ErrorList &operator=(ErrorList const &) = delete;
408
join(Error E1,Error E2)409 static Error join(Error E1, Error E2) {
410 if (!E1)
411 return E2;
412 if (!E2)
413 return E1;
414 if (E1.isA<ErrorList>()) {
415 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
416 if (E2.isA<ErrorList>()) {
417 auto E2Payload = E2.takePayload();
418 auto &E2List = static_cast<ErrorList &>(*E2Payload);
419 for (auto &Payload : E2List.Payloads)
420 E1List.Payloads.push_back(std::move(Payload));
421 } else {
422 E1List.Payloads.push_back(E2.takePayload());
423 }
424
425 return E1;
426 }
427 if (E2.isA<ErrorList>()) {
428 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
429 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
430 return E2;
431 }
432 return Error(std::unique_ptr<ErrorList>(
433 new ErrorList(E1.takePayload(), E2.takePayload())));
434 }
435
436 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
437 };
438
439 /// Concatenate errors. The resulting Error is unchecked, and contains the
440 /// ErrorInfo(s), if any, contained in E1, followed by the
441 /// ErrorInfo(s), if any, contained in E2.
joinErrors(Error E1,Error E2)442 inline Error joinErrors(Error E1, Error E2) {
443 return ErrorList::join(std::move(E1), std::move(E2));
444 }
445
446 /// Tagged union holding either a T or a Error.
447 ///
448 /// This class parallels ErrorOr, but replaces error_code with Error. Since
449 /// Error cannot be copied, this class replaces getError() with
450 /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
451 /// error class type.
452 ///
453 /// Example usage of 'Expected<T>' as a function return type:
454 ///
455 /// @code{.cpp}
456 /// Expected<int> myDivide(int A, int B) {
457 /// if (B == 0) {
458 /// // return an Error
459 /// return createStringError(inconvertibleErrorCode(),
460 /// "B must not be zero!");
461 /// }
462 /// // return an integer
463 /// return A / B;
464 /// }
465 /// @endcode
466 ///
467 /// Checking the results of to a function returning 'Expected<T>':
468 /// @code{.cpp}
469 /// if (auto E = Result.takeError()) {
470 /// // We must consume the error. Typically one of:
471 /// // - return the error to our caller
472 /// // - toString(), when logging
473 /// // - consumeError(), to silently swallow the error
474 /// // - handleErrors(), to distinguish error types
475 /// errs() << "Problem with division " << toString(std::move(E)) << "\n";
476 /// return;
477 /// }
478 /// // use the result
479 /// outs() << "The answer is " << *Result << "\n";
480 /// @endcode
481 ///
482 /// For unit-testing a function returning an 'Expected<T>', see the
483 /// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h
484
485 template <class T> class [[nodiscard]] Expected {
486 template <class T1> friend class ExpectedAsOutParameter;
487 template <class OtherT> friend class Expected;
488
489 static constexpr bool isRef = std::is_reference_v<T>;
490
491 using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
492
493 using error_type = std::unique_ptr<ErrorInfoBase>;
494
495 public:
496 using storage_type = std::conditional_t<isRef, wrap, T>;
497 using value_type = T;
498
499 private:
500 using reference = std::remove_reference_t<T> &;
501 using const_reference = const std::remove_reference_t<T> &;
502 using pointer = std::remove_reference_t<T> *;
503 using const_pointer = const std::remove_reference_t<T> *;
504
505 public:
506 /// Create an Expected<T> error value from the given Error.
Expected(Error && Err)507 Expected(Error &&Err)
508 : HasError(true)
509 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
510 // Expected is unchecked upon construction in Debug builds.
511 , Unchecked(true)
512 #endif
513 {
514 assert(Err && "Cannot create Expected<T> from Error success value.");
515 new (getErrorStorage()) error_type(Err.takePayload());
516 }
517
518 /// Forbid to convert from Error::success() implicitly, this avoids having
519 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
520 /// but triggers the assertion above.
521 Expected(ErrorSuccess) = delete;
522
523 /// Create an Expected<T> success value from the given OtherT value, which
524 /// must be convertible to T.
525 template <typename OtherT>
526 Expected(OtherT &&Val,
527 std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr)
HasError(false)528 : HasError(false)
529 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
530 // Expected is unchecked upon construction in Debug builds.
531 ,
532 Unchecked(true)
533 #endif
534 {
535 new (getStorage()) storage_type(std::forward<OtherT>(Val));
536 }
537
538 /// Move construct an Expected<T> value.
Expected(Expected && Other)539 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
540
541 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
542 /// must be convertible to T.
543 template <class OtherT>
544 Expected(Expected<OtherT> &&Other,
545 std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr) {
546 moveConstruct(std::move(Other));
547 }
548
549 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
550 /// isn't convertible to T.
551 template <class OtherT>
552 explicit Expected(
553 Expected<OtherT> &&Other,
554 std::enable_if_t<!std::is_convertible_v<OtherT, T>> * = nullptr) {
555 moveConstruct(std::move(Other));
556 }
557
558 /// Move-assign from another Expected<T>.
559 Expected &operator=(Expected &&Other) {
560 moveAssign(std::move(Other));
561 return *this;
562 }
563
564 /// Destroy an Expected<T>.
~Expected()565 ~Expected() {
566 assertIsChecked();
567 if (!HasError)
568 getStorage()->~storage_type();
569 else
570 getErrorStorage()->~error_type();
571 }
572
573 /// Return false if there is an error.
574 explicit operator bool() {
575 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
576 Unchecked = HasError;
577 #endif
578 return !HasError;
579 }
580
581 /// Returns a reference to the stored T value.
get()582 reference get() {
583 assertIsChecked();
584 return *getStorage();
585 }
586
587 /// Returns a const reference to the stored T value.
get()588 const_reference get() const {
589 assertIsChecked();
590 return const_cast<Expected<T> *>(this)->get();
591 }
592
593 /// Returns \a takeError() after moving the held T (if any) into \p V.
594 template <class OtherT>
595 Error moveInto(
596 OtherT &Value,
597 std::enable_if_t<std::is_assignable_v<OtherT &, T &&>> * = nullptr) && {
598 if (*this)
599 Value = std::move(get());
600 return takeError();
601 }
602
603 /// Check that this Expected<T> is an error of type ErrT.
errorIsA()604 template <typename ErrT> bool errorIsA() const {
605 return HasError && (*getErrorStorage())->template isA<ErrT>();
606 }
607
608 /// Take ownership of the stored error.
609 /// After calling this the Expected<T> is in an indeterminate state that can
610 /// only be safely destructed. No further calls (beside the destructor) should
611 /// be made on the Expected<T> value.
takeError()612 Error takeError() {
613 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
614 Unchecked = false;
615 #endif
616 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
617 }
618
619 /// Returns a pointer to the stored T value.
620 pointer operator->() {
621 assertIsChecked();
622 return toPointer(getStorage());
623 }
624
625 /// Returns a const pointer to the stored T value.
626 const_pointer operator->() const {
627 assertIsChecked();
628 return toPointer(getStorage());
629 }
630
631 /// Returns a reference to the stored T value.
632 reference operator*() {
633 assertIsChecked();
634 return *getStorage();
635 }
636
637 /// Returns a const reference to the stored T value.
638 const_reference operator*() const {
639 assertIsChecked();
640 return *getStorage();
641 }
642
643 private:
644 template <class T1>
compareThisIfSameType(const T1 & a,const T1 & b)645 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
646 return &a == &b;
647 }
648
649 template <class T1, class T2>
compareThisIfSameType(const T1 &,const T2 &)650 static bool compareThisIfSameType(const T1 &, const T2 &) {
651 return false;
652 }
653
moveConstruct(Expected<OtherT> && Other)654 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
655 HasError = Other.HasError;
656 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
657 Unchecked = true;
658 Other.Unchecked = false;
659 #endif
660
661 if (!HasError)
662 new (getStorage()) storage_type(std::move(*Other.getStorage()));
663 else
664 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
665 }
666
moveAssign(Expected<OtherT> && Other)667 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
668 assertIsChecked();
669
670 if (compareThisIfSameType(*this, Other))
671 return;
672
673 this->~Expected();
674 new (this) Expected(std::move(Other));
675 }
676
toPointer(pointer Val)677 pointer toPointer(pointer Val) { return Val; }
678
toPointer(const_pointer Val)679 const_pointer toPointer(const_pointer Val) const { return Val; }
680
toPointer(wrap * Val)681 pointer toPointer(wrap *Val) { return &Val->get(); }
682
toPointer(const wrap * Val)683 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
684
getStorage()685 storage_type *getStorage() {
686 assert(!HasError && "Cannot get value when an error exists!");
687 return &TStorage;
688 }
689
getStorage()690 const storage_type *getStorage() const {
691 assert(!HasError && "Cannot get value when an error exists!");
692 return &TStorage;
693 }
694
getErrorStorage()695 error_type *getErrorStorage() {
696 assert(HasError && "Cannot get error when a value exists!");
697 return &ErrorStorage;
698 }
699
getErrorStorage()700 const error_type *getErrorStorage() const {
701 assert(HasError && "Cannot get error when a value exists!");
702 return &ErrorStorage;
703 }
704
705 // Used by ExpectedAsOutParameter to reset the checked flag.
setUnchecked()706 void setUnchecked() {
707 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
708 Unchecked = true;
709 #endif
710 }
711
712 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
fatalUncheckedExpected()713 [[noreturn]] LLVM_ATTRIBUTE_NOINLINE void fatalUncheckedExpected() const {
714 dbgs() << "Expected<T> must be checked before access or destruction.\n";
715 if (HasError) {
716 dbgs() << "Unchecked Expected<T> contained error:\n";
717 (*getErrorStorage())->log(dbgs());
718 } else {
719 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
720 "values in success mode must still be checked prior to being "
721 "destroyed).\n";
722 }
723 abort();
724 }
725 #endif
726
assertIsChecked()727 void assertIsChecked() const {
728 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
729 if (LLVM_UNLIKELY(Unchecked))
730 fatalUncheckedExpected();
731 #endif
732 }
733
734 union {
735 storage_type TStorage;
736 error_type ErrorStorage;
737 };
738 bool HasError : 1;
739 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
740 bool Unchecked : 1;
741 #endif
742 };
743
744 /// @deprecated Use reportFatalInternalError() or reportFatalUsageError()
745 /// instead.
746 [[noreturn]] LLVM_ABI void report_fatal_error(Error Err,
747 bool gen_crash_diag = true);
748
749 /// Report a fatal error that indicates a bug in LLVM.
750 /// See ErrorHandling.h for details.
751 [[noreturn]] LLVM_ABI void reportFatalInternalError(Error Err);
752 /// Report a fatal error that does not indicate a bug in LLVM.
753 /// See ErrorHandling.h for details.
754 [[noreturn]] LLVM_ABI void reportFatalUsageError(Error Err);
755
756 /// Report a fatal error if Err is a failure value.
757 ///
758 /// This function can be used to wrap calls to fallible functions ONLY when it
759 /// is known that the Error will always be a success value. E.g.
760 ///
761 /// @code{.cpp}
762 /// // foo only attempts the fallible operation if DoFallibleOperation is
763 /// // true. If DoFallibleOperation is false then foo always returns
764 /// // Error::success().
765 /// Error foo(bool DoFallibleOperation);
766 ///
767 /// cantFail(foo(false));
768 /// @endcode
769 inline void cantFail(Error Err, const char *Msg = nullptr) {
770 if (Err) {
771 if (!Msg)
772 Msg = "Failure value returned from cantFail wrapped call";
773 #ifndef NDEBUG
774 std::string Str;
775 raw_string_ostream OS(Str);
776 OS << Msg << "\n" << Err;
777 Msg = Str.c_str();
778 #endif
779 llvm_unreachable(Msg);
780 }
781 }
782
783 /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
784 /// returns the contained value.
785 ///
786 /// This function can be used to wrap calls to fallible functions ONLY when it
787 /// is known that the Error will always be a success value. E.g.
788 ///
789 /// @code{.cpp}
790 /// // foo only attempts the fallible operation if DoFallibleOperation is
791 /// // true. If DoFallibleOperation is false then foo always returns an int.
792 /// Expected<int> foo(bool DoFallibleOperation);
793 ///
794 /// int X = cantFail(foo(false));
795 /// @endcode
796 template <typename T>
797 T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
798 if (ValOrErr)
799 return std::move(*ValOrErr);
800 else {
801 if (!Msg)
802 Msg = "Failure value returned from cantFail wrapped call";
803 #ifndef NDEBUG
804 std::string Str;
805 raw_string_ostream OS(Str);
806 auto E = ValOrErr.takeError();
807 OS << Msg << "\n" << E;
808 Msg = Str.c_str();
809 #endif
810 llvm_unreachable(Msg);
811 }
812 }
813
814 /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
815 /// returns the contained reference.
816 ///
817 /// This function can be used to wrap calls to fallible functions ONLY when it
818 /// is known that the Error will always be a success value. E.g.
819 ///
820 /// @code{.cpp}
821 /// // foo only attempts the fallible operation if DoFallibleOperation is
822 /// // true. If DoFallibleOperation is false then foo always returns a Bar&.
823 /// Expected<Bar&> foo(bool DoFallibleOperation);
824 ///
825 /// Bar &X = cantFail(foo(false));
826 /// @endcode
827 template <typename T>
828 T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
829 if (ValOrErr)
830 return *ValOrErr;
831 else {
832 if (!Msg)
833 Msg = "Failure value returned from cantFail wrapped call";
834 #ifndef NDEBUG
835 std::string Str;
836 raw_string_ostream OS(Str);
837 auto E = ValOrErr.takeError();
838 OS << Msg << "\n" << E;
839 Msg = Str.c_str();
840 #endif
841 llvm_unreachable(Msg);
842 }
843 }
844
845 /// Helper for testing applicability of, and applying, handlers for
846 /// ErrorInfo types.
847 template <typename HandlerT>
848 class ErrorHandlerTraits
849 : public ErrorHandlerTraits<
850 decltype(&std::remove_reference_t<HandlerT>::operator())> {};
851
852 // Specialization functions of the form 'Error (const ErrT&)'.
853 template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
854 public:
appliesTo(const ErrorInfoBase & E)855 static bool appliesTo(const ErrorInfoBase &E) {
856 return E.template isA<ErrT>();
857 }
858
859 template <typename HandlerT>
apply(HandlerT && H,std::unique_ptr<ErrorInfoBase> E)860 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
861 assert(appliesTo(*E) && "Applying incorrect handler");
862 return H(static_cast<ErrT &>(*E));
863 }
864 };
865
866 // Specialization functions of the form 'void (const ErrT&)'.
867 template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
868 public:
appliesTo(const ErrorInfoBase & E)869 static bool appliesTo(const ErrorInfoBase &E) {
870 return E.template isA<ErrT>();
871 }
872
873 template <typename HandlerT>
apply(HandlerT && H,std::unique_ptr<ErrorInfoBase> E)874 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
875 assert(appliesTo(*E) && "Applying incorrect handler");
876 H(static_cast<ErrT &>(*E));
877 return Error::success();
878 }
879 };
880
881 /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
882 template <typename ErrT>
883 class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
884 public:
appliesTo(const ErrorInfoBase & E)885 static bool appliesTo(const ErrorInfoBase &E) {
886 return E.template isA<ErrT>();
887 }
888
889 template <typename HandlerT>
apply(HandlerT && H,std::unique_ptr<ErrorInfoBase> E)890 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
891 assert(appliesTo(*E) && "Applying incorrect handler");
892 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
893 return H(std::move(SubE));
894 }
895 };
896
897 /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
898 template <typename ErrT>
899 class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
900 public:
appliesTo(const ErrorInfoBase & E)901 static bool appliesTo(const ErrorInfoBase &E) {
902 return E.template isA<ErrT>();
903 }
904
905 template <typename HandlerT>
apply(HandlerT && H,std::unique_ptr<ErrorInfoBase> E)906 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
907 assert(appliesTo(*E) && "Applying incorrect handler");
908 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
909 H(std::move(SubE));
910 return Error::success();
911 }
912 };
913
914 // Specialization for member functions of the form 'RetT (const ErrT&)'.
915 template <typename C, typename RetT, typename ErrT>
916 class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
917 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
918
919 // Specialization for member functions of the form 'RetT (const ErrT&) const'.
920 template <typename C, typename RetT, typename ErrT>
921 class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
922 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
923
924 // Specialization for member functions of the form 'RetT (const ErrT&)'.
925 template <typename C, typename RetT, typename ErrT>
926 class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
927 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
928
929 // Specialization for member functions of the form 'RetT (const ErrT&) const'.
930 template <typename C, typename RetT, typename ErrT>
931 class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
932 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
933
934 /// Specialization for member functions of the form
935 /// 'RetT (std::unique_ptr<ErrT>)'.
936 template <typename C, typename RetT, typename ErrT>
937 class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
938 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
939
940 /// Specialization for member functions of the form
941 /// 'RetT (std::unique_ptr<ErrT>) const'.
942 template <typename C, typename RetT, typename ErrT>
943 class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
944 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
945
handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload)946 inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
947 return Error(std::move(Payload));
948 }
949
950 template <typename HandlerT, typename... HandlerTs>
handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,HandlerT && Handler,HandlerTs &&...Handlers)951 Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
952 HandlerT &&Handler, HandlerTs &&... Handlers) {
953 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
954 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
955 std::move(Payload));
956 return handleErrorImpl(std::move(Payload),
957 std::forward<HandlerTs>(Handlers)...);
958 }
959
960 /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
961 /// unhandled errors (or Errors returned by handlers) are re-concatenated and
962 /// returned.
963 /// Because this function returns an error, its result must also be checked
964 /// or returned. If you intend to handle all errors use handleAllErrors
965 /// (which returns void, and will abort() on unhandled errors) instead.
966 template <typename... HandlerTs>
handleErrors(Error E,HandlerTs &&...Hs)967 Error handleErrors(Error E, HandlerTs &&... Hs) {
968 if (!E)
969 return Error::success();
970
971 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
972
973 if (Payload->isA<ErrorList>()) {
974 ErrorList &List = static_cast<ErrorList &>(*Payload);
975 Error R;
976 for (auto &P : List.Payloads)
977 R = ErrorList::join(
978 std::move(R),
979 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
980 return R;
981 }
982
983 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
984 }
985
986 /// Behaves the same as handleErrors, except that by contract all errors
987 /// *must* be handled by the given handlers (i.e. there must be no remaining
988 /// errors after running the handlers, or llvm_unreachable is called).
989 template <typename... HandlerTs>
handleAllErrors(Error E,HandlerTs &&...Handlers)990 void handleAllErrors(Error E, HandlerTs &&... Handlers) {
991 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
992 }
993
994 /// Check that E is a non-error, then drop it.
995 /// If E is an error, llvm_unreachable will be called.
handleAllErrors(Error E)996 inline void handleAllErrors(Error E) {
997 cantFail(std::move(E));
998 }
999
1000 /// Visit all the ErrorInfo(s) contained in E by passing them to the respective
1001 /// handler, without consuming the error.
visitErrors(const Error & E,HandlerT H)1002 template <typename HandlerT> void visitErrors(const Error &E, HandlerT H) {
1003 const ErrorInfoBase *Payload = E.getPtr();
1004 if (!Payload)
1005 return;
1006
1007 if (Payload->isA<ErrorList>()) {
1008 const ErrorList &List = static_cast<const ErrorList &>(*Payload);
1009 for (const auto &P : List.Payloads)
1010 H(*P);
1011 return;
1012 }
1013
1014 return H(*Payload);
1015 }
1016
1017 /// Handle any errors (if present) in an Expected<T>, then try a recovery path.
1018 ///
1019 /// If the incoming value is a success value it is returned unmodified. If it
1020 /// is a failure value then it the contained error is passed to handleErrors.
1021 /// If handleErrors is able to handle the error then the RecoveryPath functor
1022 /// is called to supply the final result. If handleErrors is not able to
1023 /// handle all errors then the unhandled errors are returned.
1024 ///
1025 /// This utility enables the follow pattern:
1026 ///
1027 /// @code{.cpp}
1028 /// enum FooStrategy { Aggressive, Conservative };
1029 /// Expected<Foo> foo(FooStrategy S);
1030 ///
1031 /// auto ResultOrErr =
1032 /// handleExpected(
1033 /// foo(Aggressive),
1034 /// []() { return foo(Conservative); },
1035 /// [](AggressiveStrategyError&) {
1036 /// // Implicitly conusme this - we'll recover by using a conservative
1037 /// // strategy.
1038 /// });
1039 ///
1040 /// @endcode
1041 template <typename T, typename RecoveryFtor, typename... HandlerTs>
handleExpected(Expected<T> ValOrErr,RecoveryFtor && RecoveryPath,HandlerTs &&...Handlers)1042 Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
1043 HandlerTs &&... Handlers) {
1044 if (ValOrErr)
1045 return ValOrErr;
1046
1047 if (auto Err = handleErrors(ValOrErr.takeError(),
1048 std::forward<HandlerTs>(Handlers)...))
1049 return std::move(Err);
1050
1051 return RecoveryPath();
1052 }
1053
1054 /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
1055 /// will be printed before the first one is logged. A newline will be printed
1056 /// after each error.
1057 ///
1058 /// This function is compatible with the helpers from Support/WithColor.h. You
1059 /// can pass any of them as the OS. Please consider using them instead of
1060 /// including 'error: ' in the ErrorBanner.
1061 ///
1062 /// This is useful in the base level of your program to allow clean termination
1063 /// (allowing clean deallocation of resources, etc.), while reporting error
1064 /// information to the user.
1065 LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS,
1066 Twine ErrorBanner = {});
1067
1068 /// Write all error messages (if any) in E to a string. The newline character
1069 /// is used to separate error messages.
1070 LLVM_ABI std::string toString(Error E);
1071
1072 /// Like toString(), but does not consume the error. This can be used to print
1073 /// a warning while retaining the original error object.
1074 LLVM_ABI std::string toStringWithoutConsuming(const Error &E);
1075
1076 /// Consume a Error without doing anything. This method should be used
1077 /// only where an error can be considered a reasonable and expected return
1078 /// value.
1079 ///
1080 /// Uses of this method are potentially indicative of design problems: If it's
1081 /// legitimate to do nothing while processing an "error", the error-producer
1082 /// might be more clearly refactored to return an std::optional<T>.
consumeError(Error Err)1083 inline void consumeError(Error Err) {
1084 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
1085 }
1086
1087 /// Convert an Expected to an Optional without doing anything. This method
1088 /// should be used only where an error can be considered a reasonable and
1089 /// expected return value.
1090 ///
1091 /// Uses of this method are potentially indicative of problems: perhaps the
1092 /// error should be propagated further, or the error-producer should just
1093 /// return an Optional in the first place.
expectedToOptional(Expected<T> && E)1094 template <typename T> std::optional<T> expectedToOptional(Expected<T> &&E) {
1095 if (E)
1096 return std::move(*E);
1097 consumeError(E.takeError());
1098 return std::nullopt;
1099 }
1100
expectedToStdOptional(Expected<T> && E)1101 template <typename T> std::optional<T> expectedToStdOptional(Expected<T> &&E) {
1102 if (E)
1103 return std::move(*E);
1104 consumeError(E.takeError());
1105 return std::nullopt;
1106 }
1107
1108 /// Helper for converting an Error to a bool.
1109 ///
1110 /// This method returns true if Err is in an error state, or false if it is
1111 /// in a success state. Puts Err in a checked state in both cases (unlike
1112 /// Error::operator bool(), which only does this for success states).
errorToBool(Error Err)1113 inline bool errorToBool(Error Err) {
1114 bool IsError = static_cast<bool>(Err);
1115 if (IsError)
1116 consumeError(std::move(Err));
1117 return IsError;
1118 }
1119
1120 /// Helper for Errors used as out-parameters.
1121 ///
1122 /// This helper is for use with the Error-as-out-parameter idiom, where an error
1123 /// is passed to a function or method by reference, rather than being returned.
1124 /// In such cases it is helpful to set the checked bit on entry to the function
1125 /// so that the error can be written to (unchecked Errors abort on assignment)
1126 /// and clear the checked bit on exit so that clients cannot accidentally forget
1127 /// to check the result. This helper performs these actions automatically using
1128 /// RAII:
1129 ///
1130 /// @code{.cpp}
1131 /// Result foo(Error &Err) {
1132 /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1133 /// // <body of foo>
1134 /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1135 /// }
1136 /// @endcode
1137 ///
1138 /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1139 /// used with optional Errors (Error pointers that are allowed to be null). If
1140 /// ErrorAsOutParameter took an Error reference, an instance would have to be
1141 /// created inside every condition that verified that Error was non-null. By
1142 /// taking an Error pointer we can just create one instance at the top of the
1143 /// function.
1144 class ErrorAsOutParameter {
1145 public:
1146
ErrorAsOutParameter(Error * Err)1147 ErrorAsOutParameter(Error *Err) : Err(Err) {
1148 // Raise the checked bit if Err is success.
1149 if (Err)
1150 (void)!!*Err;
1151 }
1152
ErrorAsOutParameter(Error & Err)1153 ErrorAsOutParameter(Error &Err) : Err(&Err) {
1154 (void)!!Err;
1155 }
1156
~ErrorAsOutParameter()1157 ~ErrorAsOutParameter() {
1158 // Clear the checked bit.
1159 if (Err && !*Err)
1160 *Err = Error::success();
1161 }
1162
1163 private:
1164 Error *Err;
1165 };
1166
1167 /// Helper for Expected<T>s used as out-parameters.
1168 ///
1169 /// See ErrorAsOutParameter.
1170 template <typename T>
1171 class ExpectedAsOutParameter {
1172 public:
ExpectedAsOutParameter(Expected<T> * ValOrErr)1173 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1174 : ValOrErr(ValOrErr) {
1175 if (ValOrErr)
1176 (void)!!*ValOrErr;
1177 }
1178
~ExpectedAsOutParameter()1179 ~ExpectedAsOutParameter() {
1180 if (ValOrErr)
1181 ValOrErr->setUnchecked();
1182 }
1183
1184 private:
1185 Expected<T> *ValOrErr;
1186 };
1187
1188 /// This class wraps a std::error_code in a Error.
1189 ///
1190 /// This is useful if you're writing an interface that returns a Error
1191 /// (or Expected) and you want to call code that still returns
1192 /// std::error_codes.
1193 class LLVM_ABI ECError : public ErrorInfo<ECError> {
1194 LLVM_ABI friend Error errorCodeToError(std::error_code);
1195
1196 void anchor() override;
1197
1198 public:
setErrorCode(std::error_code EC)1199 void setErrorCode(std::error_code EC) { this->EC = EC; }
convertToErrorCode()1200 std::error_code convertToErrorCode() const override { return EC; }
log(raw_ostream & OS)1201 void log(raw_ostream &OS) const override { OS << EC.message(); }
1202
1203 // Used by ErrorInfo::classID.
1204 static char ID;
1205
1206 protected:
1207 ECError() = default;
ECError(std::error_code EC)1208 ECError(std::error_code EC) : EC(EC) {}
1209
1210 std::error_code EC;
1211 };
1212
1213 /// The value returned by this function can be returned from convertToErrorCode
1214 /// for Error values where no sensible translation to std::error_code exists.
1215 /// It should only be used in this situation, and should never be used where a
1216 /// sensible conversion to std::error_code is available, as attempts to convert
1217 /// to/from this error will result in a fatal error. (i.e. it is a programmatic
1218 /// error to try to convert such a value).
1219 LLVM_ABI std::error_code inconvertibleErrorCode();
1220
1221 /// Helper for converting an std::error_code to a Error.
1222 LLVM_ABI Error errorCodeToError(std::error_code EC);
1223
1224 /// Helper for converting an ECError to a std::error_code.
1225 ///
1226 /// This method requires that Err be Error() or an ECError, otherwise it
1227 /// will trigger a call to abort().
1228 LLVM_ABI std::error_code errorToErrorCode(Error Err);
1229
1230 /// Helper to get errno as an std::error_code.
1231 ///
1232 /// errno should always be represented using the generic category as that's what
1233 /// both libc++ and libstdc++ do. On POSIX systems you can also represent them
1234 /// using the system category, however this makes them compare differently for
1235 /// values outside of those used by `std::errc` if one is generic and the other
1236 /// is system.
1237 ///
1238 /// See the libc++ and libstdc++ implementations of `default_error_condition` on
1239 /// the system category for more details on what the difference is.
errnoAsErrorCode()1240 inline std::error_code errnoAsErrorCode() {
1241 return std::error_code(errno, std::generic_category());
1242 }
1243
1244 /// Convert an ErrorOr<T> to an Expected<T>.
errorOrToExpected(ErrorOr<T> && EO)1245 template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1246 if (auto EC = EO.getError())
1247 return errorCodeToError(EC);
1248 return std::move(*EO);
1249 }
1250
1251 /// Convert an Expected<T> to an ErrorOr<T>.
expectedToErrorOr(Expected<T> && E)1252 template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1253 if (auto Err = E.takeError())
1254 return errorToErrorCode(std::move(Err));
1255 return std::move(*E);
1256 }
1257
1258 /// This class wraps a string in an Error.
1259 ///
1260 /// StringError is useful in cases where the client is not expected to be able
1261 /// to consume the specific error message programmatically (for example, if the
1262 /// error message is to be presented to the user).
1263 ///
1264 /// StringError can also be used when additional information is to be printed
1265 /// along with a error_code message. Depending on the constructor called, this
1266 /// class can either display:
1267 /// 1. the error_code message (ECError behavior)
1268 /// 2. a string
1269 /// 3. the error_code message and a string
1270 ///
1271 /// These behaviors are useful when subtyping is required; for example, when a
1272 /// specific library needs an explicit error type. In the example below,
1273 /// PDBError is derived from StringError:
1274 ///
1275 /// @code{.cpp}
1276 /// Expected<int> foo() {
1277 /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1278 /// "Additional information");
1279 /// }
1280 /// @endcode
1281 ///
1282 class LLVM_ABI StringError : public ErrorInfo<StringError> {
1283 public:
1284 static char ID;
1285
1286 StringError(std::string &&S, std::error_code EC, bool PrintMsgOnly);
1287 /// Prints EC + S and converts to EC.
1288 StringError(std::error_code EC, const Twine &S = Twine());
1289 /// Prints S and converts to EC.
1290 StringError(const Twine &S, std::error_code EC);
1291
1292 void log(raw_ostream &OS) const override;
1293 std::error_code convertToErrorCode() const override;
1294
getMessage()1295 const std::string &getMessage() const { return Msg; }
1296
1297 private:
1298 std::string Msg;
1299 std::error_code EC;
1300 const bool PrintMsgOnly = false;
1301 };
1302
1303 /// Create formatted StringError object.
1304 template <typename... Ts>
createStringError(std::error_code EC,char const * Fmt,const Ts &...Vals)1305 inline Error createStringError(std::error_code EC, char const *Fmt,
1306 const Ts &... Vals) {
1307 std::string Buffer;
1308 raw_string_ostream(Buffer) << format(Fmt, Vals...);
1309 return make_error<StringError>(Buffer, EC);
1310 }
1311
1312 LLVM_ABI Error createStringError(std::string &&Msg, std::error_code EC);
1313
createStringError(std::error_code EC,const char * S)1314 inline Error createStringError(std::error_code EC, const char *S) {
1315 return createStringError(std::string(S), EC);
1316 }
1317
createStringError(std::error_code EC,const Twine & S)1318 inline Error createStringError(std::error_code EC, const Twine &S) {
1319 return createStringError(S.str(), EC);
1320 }
1321
1322 /// Create a StringError with an inconvertible error code.
createStringError(const Twine & S)1323 inline Error createStringError(const Twine &S) {
1324 return createStringError(llvm::inconvertibleErrorCode(), S);
1325 }
1326
1327 template <typename... Ts>
createStringError(char const * Fmt,const Ts &...Vals)1328 inline Error createStringError(char const *Fmt, const Ts &...Vals) {
1329 return createStringError(llvm::inconvertibleErrorCode(), Fmt, Vals...);
1330 }
1331
1332 template <typename... Ts>
createStringError(std::errc EC,char const * Fmt,const Ts &...Vals)1333 inline Error createStringError(std::errc EC, char const *Fmt,
1334 const Ts &... Vals) {
1335 return createStringError(std::make_error_code(EC), Fmt, Vals...);
1336 }
1337
1338 /// This class wraps a filename and another Error.
1339 ///
1340 /// In some cases, an error needs to live along a 'source' name, in order to
1341 /// show more detailed information to the user.
1342 class LLVM_ABI FileError final : public ErrorInfo<FileError> {
1343
1344 friend Error createFileError(const Twine &, Error);
1345 friend Error createFileError(const Twine &, size_t, Error);
1346
1347 public:
log(raw_ostream & OS)1348 void log(raw_ostream &OS) const override {
1349 assert(Err && "Trying to log after takeError().");
1350 OS << "'" << FileName << "': ";
1351 if (Line)
1352 OS << "line " << *Line << ": ";
1353 Err->log(OS);
1354 }
1355
messageWithoutFileInfo()1356 std::string messageWithoutFileInfo() const {
1357 std::string Msg;
1358 raw_string_ostream OS(Msg);
1359 Err->log(OS);
1360 return Msg;
1361 }
1362
getFileName()1363 StringRef getFileName() const { return FileName; }
1364
takeError()1365 Error takeError() { return Error(std::move(Err)); }
1366
1367 std::error_code convertToErrorCode() const override;
1368
1369 // Used by ErrorInfo::classID.
1370 static char ID;
1371
1372 private:
FileError(const Twine & F,std::optional<size_t> LineNum,std::unique_ptr<ErrorInfoBase> E)1373 FileError(const Twine &F, std::optional<size_t> LineNum,
1374 std::unique_ptr<ErrorInfoBase> E) {
1375 assert(E && "Cannot create FileError from Error success value.");
1376 FileName = F.str();
1377 Err = std::move(E);
1378 Line = std::move(LineNum);
1379 }
1380
build(const Twine & F,std::optional<size_t> Line,Error E)1381 static Error build(const Twine &F, std::optional<size_t> Line, Error E) {
1382 std::unique_ptr<ErrorInfoBase> Payload;
1383 handleAllErrors(std::move(E),
1384 [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error {
1385 Payload = std::move(EIB);
1386 return Error::success();
1387 });
1388 return Error(
1389 std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload))));
1390 }
1391
1392 std::string FileName;
1393 std::optional<size_t> Line;
1394 std::unique_ptr<ErrorInfoBase> Err;
1395 };
1396
1397 /// Concatenate a source file path and/or name with an Error. The resulting
1398 /// Error is unchecked.
createFileError(const Twine & F,Error E)1399 inline Error createFileError(const Twine &F, Error E) {
1400 return FileError::build(F, std::optional<size_t>(), std::move(E));
1401 }
1402
1403 /// Concatenate a source file path and/or name with line number and an Error.
1404 /// The resulting Error is unchecked.
createFileError(const Twine & F,size_t Line,Error E)1405 inline Error createFileError(const Twine &F, size_t Line, Error E) {
1406 return FileError::build(F, std::optional<size_t>(Line), std::move(E));
1407 }
1408
1409 /// Concatenate a source file path and/or name with a std::error_code
1410 /// to form an Error object.
createFileError(const Twine & F,std::error_code EC)1411 inline Error createFileError(const Twine &F, std::error_code EC) {
1412 return createFileError(F, errorCodeToError(EC));
1413 }
1414
1415 /// Concatenate a source file path and/or name with line number and
1416 /// std::error_code to form an Error object.
createFileError(const Twine & F,size_t Line,std::error_code EC)1417 inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1418 return createFileError(F, Line, errorCodeToError(EC));
1419 }
1420
1421 /// Create a StringError with the specified error code and prepend the file path
1422 /// to it.
createFileError(const Twine & F,std::error_code EC,const Twine & S)1423 inline Error createFileError(const Twine &F, std::error_code EC,
1424 const Twine &S) {
1425 Error E = createStringError(EC, S);
1426 return createFileError(F, std::move(E));
1427 }
1428
1429 /// Create a StringError with the specified error code and prepend the file path
1430 /// to it.
1431 template <typename... Ts>
createFileError(const Twine & F,std::error_code EC,char const * Fmt,const Ts &...Vals)1432 inline Error createFileError(const Twine &F, std::error_code EC,
1433 char const *Fmt, const Ts &...Vals) {
1434 Error E = createStringError(EC, Fmt, Vals...);
1435 return createFileError(F, std::move(E));
1436 }
1437
1438 Error createFileError(const Twine &F, ErrorSuccess) = delete;
1439
1440 /// Helper for check-and-exit error handling.
1441 ///
1442 /// For tool use only. NOT FOR USE IN LIBRARY CODE.
1443 ///
1444 class ExitOnError {
1445 public:
1446 /// Create an error on exit helper.
1447 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
Banner(std::move (Banner))1448 : Banner(std::move(Banner)),
1449 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1450
1451 /// Set the banner string for any errors caught by operator().
setBanner(std::string Banner)1452 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1453
1454 /// Set the exit-code mapper function.
setExitCodeMapper(std::function<int (const Error &)> GetExitCode)1455 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1456 this->GetExitCode = std::move(GetExitCode);
1457 }
1458
1459 /// Check Err. If it's in a failure state log the error(s) and exit.
operator()1460 void operator()(Error Err) const { checkError(std::move(Err)); }
1461
1462 /// Check E. If it's in a success state then return the contained value. If
1463 /// it's in a failure state log the error(s) and exit.
operator()1464 template <typename T> T operator()(Expected<T> &&E) const {
1465 checkError(E.takeError());
1466 return std::move(*E);
1467 }
1468
1469 /// Check E. If it's in a success state then return the contained reference. If
1470 /// it's in a failure state log the error(s) and exit.
operator()1471 template <typename T> T& operator()(Expected<T&> &&E) const {
1472 checkError(E.takeError());
1473 return *E;
1474 }
1475
1476 private:
checkError(Error Err)1477 void checkError(Error Err) const {
1478 if (Err) {
1479 int ExitCode = GetExitCode(Err);
1480 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1481 exit(ExitCode);
1482 }
1483 }
1484
1485 std::string Banner;
1486 std::function<int(const Error &)> GetExitCode;
1487 };
1488
1489 /// Conversion from Error to LLVMErrorRef for C error bindings.
wrap(Error Err)1490 inline LLVMErrorRef wrap(Error Err) {
1491 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1492 }
1493
1494 /// Conversion from LLVMErrorRef to Error for C error bindings.
unwrap(LLVMErrorRef ErrRef)1495 inline Error unwrap(LLVMErrorRef ErrRef) {
1496 return Error(std::unique_ptr<ErrorInfoBase>(
1497 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1498 }
1499
1500 } // end namespace llvm
1501
1502 #endif // LLVM_SUPPORT_ERROR_H
1503