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/raw_ostream.h" 28#include <algorithm> 29#include <cassert> 30#include <cstdint> 31#include <cstdlib> 32#include <functional> 33#include <memory> 34#include <new> 35#include <string> 36#include <system_error> 37#include <type_traits> 38#include <utility> 39#include <vector> 40 41namespace llvm { 42 43class ErrorSuccess; 44 45/// Base class for error info classes. Do not extend this directly: Extend 46/// the ErrorInfo template subclass instead. 47class ErrorInfoBase { 48public: 49 virtual ~ErrorInfoBase() = default; 50 51 /// Print an error message to an output stream. 52 virtual void log(raw_ostream &OS) const = 0; 53 54 /// Return the error message as a string. 55 virtual std::string message() const { 56 std::string Msg; 57 raw_string_ostream OS(Msg); 58 log(OS); 59 return OS.str(); 60 } 61 62 /// Convert this error to a std::error_code. 63 /// 64 /// This is a temporary crutch to enable interaction with code still 65 /// using std::error_code. It will be removed in the future. 66 virtual std::error_code convertToErrorCode() const = 0; 67 68 // Returns the class ID for this type. 69 static const void *classID() { return &ID; } 70 71 // Returns the class ID for the dynamic type of this ErrorInfoBase instance. 72 virtual const void *dynamicClassID() const = 0; 73 74 // Check whether this instance is a subclass of the class identified by 75 // ClassID. 76 virtual bool isA(const void *const ClassID) const { 77 return ClassID == classID(); 78 } 79 80 // Check whether this instance is a subclass of ErrorInfoT. 81 template <typename ErrorInfoT> bool isA() const { 82 return isA(ErrorInfoT::classID()); 83 } 84 85private: 86 virtual void anchor(); 87 88 static char ID; 89}; 90 91/// Lightweight error class with error context and mandatory checking. 92/// 93/// Instances of this class wrap a ErrorInfoBase pointer. Failure states 94/// are represented by setting the pointer to a ErrorInfoBase subclass 95/// instance containing information describing the failure. Success is 96/// represented by a null pointer value. 97/// 98/// Instances of Error also contains a 'Checked' flag, which must be set 99/// before the destructor is called, otherwise the destructor will trigger a 100/// runtime error. This enforces at runtime the requirement that all Error 101/// instances be checked or returned to the caller. 102/// 103/// There are two ways to set the checked flag, depending on what state the 104/// Error instance is in. For Error instances indicating success, it 105/// is sufficient to invoke the boolean conversion operator. E.g.: 106/// 107/// @code{.cpp} 108/// Error foo(<...>); 109/// 110/// if (auto E = foo(<...>)) 111/// return E; // <- Return E if it is in the error state. 112/// // We have verified that E was in the success state. It can now be safely 113/// // destroyed. 114/// @endcode 115/// 116/// A success value *can not* be dropped. For example, just calling 'foo(<...>)' 117/// without testing the return value will raise a runtime error, even if foo 118/// returns success. 119/// 120/// For Error instances representing failure, you must use either the 121/// handleErrors or handleAllErrors function with a typed handler. E.g.: 122/// 123/// @code{.cpp} 124/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { 125/// // Custom error info. 126/// }; 127/// 128/// Error foo(<...>) { return make_error<MyErrorInfo>(...); } 129/// 130/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. 131/// auto NewE = 132/// handleErrors(E, 133/// [](const MyErrorInfo &M) { 134/// // Deal with the error. 135/// }, 136/// [](std::unique_ptr<OtherError> M) -> Error { 137/// if (canHandle(*M)) { 138/// // handle error. 139/// return Error::success(); 140/// } 141/// // Couldn't handle this error instance. Pass it up the stack. 142/// return Error(std::move(M)); 143/// ); 144/// // Note - we must check or return NewE in case any of the handlers 145/// // returned a new error. 146/// @endcode 147/// 148/// The handleAllErrors function is identical to handleErrors, except 149/// that it has a void return type, and requires all errors to be handled and 150/// no new errors be returned. It prevents errors (assuming they can all be 151/// handled) from having to be bubbled all the way to the top-level. 152/// 153/// *All* Error instances must be checked before destruction, even if 154/// they're moved-assigned or constructed from Success values that have already 155/// been checked. This enforces checking through all levels of the call stack. 156class LLVM_NODISCARD Error { 157 // ErrorList needs to be able to yank ErrorInfoBase pointers out of this 158 // class to add to the error list. 159 friend class ErrorList; 160 161 // handleErrors needs to be able to set the Checked flag. 162 template <typename... HandlerTs> 163 friend Error handleErrors(Error E, HandlerTs &&... Handlers); 164 165 // Expected<T> needs to be able to steal the payload when constructed from an 166 // error. 167 template <typename T> friend class Expected; 168 169protected: 170 /// Create a success value. Prefer using 'Error::success()' for readability 171 Error() { 172 setPtr(nullptr); 173 setChecked(false); 174 } 175 176public: 177 /// Create a success value. 178 static ErrorSuccess success(); 179 180 // Errors are not copy-constructable. 181 Error(const Error &Other) = delete; 182 183 /// Move-construct an error value. The newly constructed error is considered 184 /// unchecked, even if the source error had been checked. The original error 185 /// becomes a checked Success value, regardless of its original state. 186 Error(Error &&Other) { 187 setChecked(true); 188 *this = std::move(Other); 189 } 190 191 /// Create an error value. Prefer using the 'make_error' function, but 192 /// this constructor can be useful when "re-throwing" errors from handlers. 193 Error(std::unique_ptr<ErrorInfoBase> Payload) { 194 setPtr(Payload.release()); 195 setChecked(false); 196 } 197 198 // Errors are not copy-assignable. 199 Error &operator=(const Error &Other) = delete; 200 201 /// Move-assign an error value. The current error must represent success, you 202 /// you cannot overwrite an unhandled error. The current error is then 203 /// considered unchecked. The source error becomes a checked success value, 204 /// regardless of its original state. 205 Error &operator=(Error &&Other) { 206 // Don't allow overwriting of unchecked values. 207 assertIsChecked(); 208 setPtr(Other.getPtr()); 209 210 // This Error is unchecked, even if the source error was checked. 211 setChecked(false); 212 213 // Null out Other's payload and set its checked bit. 214 Other.setPtr(nullptr); 215 Other.setChecked(true); 216 217 return *this; 218 } 219 220 /// Destroy a Error. Fails with a call to abort() if the error is 221 /// unchecked. 222 ~Error() { 223 assertIsChecked(); 224 delete getPtr(); 225 } 226 227 /// Bool conversion. Returns true if this Error is in a failure state, 228 /// and false if it is in an accept state. If the error is in a Success state 229 /// it will be considered checked. 230 explicit operator bool() { 231 setChecked(getPtr() == nullptr); 232 return getPtr() != nullptr; 233 } 234 235 /// Check whether one error is a subclass of another. 236 template <typename ErrT> bool isA() const { 237 return getPtr() && getPtr()->isA(ErrT::classID()); 238 } 239 240 /// Returns the dynamic class id of this error, or null if this is a success 241 /// value. 242 const void* dynamicClassID() const { 243 if (!getPtr()) 244 return nullptr; 245 return getPtr()->dynamicClassID(); 246 } 247 248private: 249 void assertIsChecked() { 250#if LLVM_ENABLE_ABI_BREAKING_CHECKS 251 if (!getChecked() || getPtr()) { 252 dbgs() << "Program aborted due to an unhandled Error:\n"; 253 if (getPtr()) 254 getPtr()->log(dbgs()); 255 else 256 dbgs() 257 << "Error value was Success. (Note: Success values must still be " 258 "checked prior to being destroyed).\n"; 259 abort(); 260 } 261#endif 262 } 263 264 ErrorInfoBase *getPtr() const { 265 return reinterpret_cast<ErrorInfoBase*>( 266 reinterpret_cast<uintptr_t>(Payload) & 267 ~static_cast<uintptr_t>(0x1)); 268 } 269 270 void setPtr(ErrorInfoBase *EI) { 271#if LLVM_ENABLE_ABI_BREAKING_CHECKS 272 Payload = reinterpret_cast<ErrorInfoBase*>( 273 (reinterpret_cast<uintptr_t>(EI) & 274 ~static_cast<uintptr_t>(0x1)) | 275 (reinterpret_cast<uintptr_t>(Payload) & 0x1)); 276#else 277 Payload = EI; 278#endif 279 } 280 281 bool getChecked() const { 282#if LLVM_ENABLE_ABI_BREAKING_CHECKS 283 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; 284#else 285 return true; 286#endif 287 } 288 289 void setChecked(bool V) { 290 Payload = reinterpret_cast<ErrorInfoBase*>( 291 (reinterpret_cast<uintptr_t>(Payload) & 292 ~static_cast<uintptr_t>(0x1)) | 293 (V ? 0 : 1)); 294 } 295 296 std::unique_ptr<ErrorInfoBase> takePayload() { 297 std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); 298 setPtr(nullptr); 299 setChecked(true); 300 return Tmp; 301 } 302 303 ErrorInfoBase *Payload = nullptr; 304}; 305 306/// Subclass of Error for the sole purpose of identifying the success path in 307/// the type system. This allows to catch invalid conversion to Expected<T> at 308/// compile time. 309class ErrorSuccess : public Error {}; 310 311inline ErrorSuccess Error::success() { return ErrorSuccess(); } 312 313/// Make a Error instance representing failure using the given error info 314/// type. 315template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { 316 return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); 317} 318 319/// Base class for user error types. Users should declare their error types 320/// like: 321/// 322/// class MyError : public ErrorInfo<MyError> { 323/// .... 324/// }; 325/// 326/// This class provides an implementation of the ErrorInfoBase::kind 327/// method, which is used by the Error RTTI system. 328template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> 329class ErrorInfo : public ParentErrT { 330public: 331 static const void *classID() { return &ThisErrT::ID; } 332 333 const void *dynamicClassID() const override { return &ThisErrT::ID; } 334 335 bool isA(const void *const ClassID) const override { 336 return ClassID == classID() || ParentErrT::isA(ClassID); 337 } 338}; 339 340/// Special ErrorInfo subclass representing a list of ErrorInfos. 341/// Instances of this class are constructed by joinError. 342class ErrorList final : public ErrorInfo<ErrorList> { 343 // handleErrors needs to be able to iterate the payload list of an 344 // ErrorList. 345 template <typename... HandlerTs> 346 friend Error handleErrors(Error E, HandlerTs &&... Handlers); 347 348 // joinErrors is implemented in terms of join. 349 friend Error joinErrors(Error, Error); 350 351public: 352 void log(raw_ostream &OS) const override { 353 OS << "Multiple errors:\n"; 354 for (auto &ErrPayload : Payloads) { 355 ErrPayload->log(OS); 356 OS << "\n"; 357 } 358 } 359 360 std::error_code convertToErrorCode() const override; 361 362 // Used by ErrorInfo::classID. 363 static char ID; 364 365private: 366 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, 367 std::unique_ptr<ErrorInfoBase> Payload2) { 368 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && 369 "ErrorList constructor payloads should be singleton errors"); 370 Payloads.push_back(std::move(Payload1)); 371 Payloads.push_back(std::move(Payload2)); 372 } 373 374 static Error join(Error E1, Error E2) { 375 if (!E1) 376 return E2; 377 if (!E2) 378 return E1; 379 if (E1.isA<ErrorList>()) { 380 auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); 381 if (E2.isA<ErrorList>()) { 382 auto E2Payload = E2.takePayload(); 383 auto &E2List = static_cast<ErrorList &>(*E2Payload); 384 for (auto &Payload : E2List.Payloads) 385 E1List.Payloads.push_back(std::move(Payload)); 386 } else 387 E1List.Payloads.push_back(E2.takePayload()); 388 389 return E1; 390 } 391 if (E2.isA<ErrorList>()) { 392 auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); 393 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); 394 return E2; 395 } 396 return Error(std::unique_ptr<ErrorList>( 397 new ErrorList(E1.takePayload(), E2.takePayload()))); 398 } 399 400 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; 401}; 402 403/// Concatenate errors. The resulting Error is unchecked, and contains the 404/// ErrorInfo(s), if any, contained in E1, followed by the 405/// ErrorInfo(s), if any, contained in E2. 406inline Error joinErrors(Error E1, Error E2) { 407 return ErrorList::join(std::move(E1), std::move(E2)); 408} 409 410/// Tagged union holding either a T or a Error. 411/// 412/// This class parallels ErrorOr, but replaces error_code with Error. Since 413/// Error cannot be copied, this class replaces getError() with 414/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the 415/// error class type. 416template <class T> class LLVM_NODISCARD Expected { 417 template <class T1> friend class ExpectedAsOutParameter; 418 template <class OtherT> friend class Expected; 419 420 static const bool isRef = std::is_reference<T>::value; 421 422 using wrap = ReferenceStorage<typename std::remove_reference<T>::type>; 423 424 using error_type = std::unique_ptr<ErrorInfoBase>; 425 426public: 427 using storage_type = typename std::conditional<isRef, wrap, T>::type; 428 using value_type = T; 429 430private: 431 using reference = typename std::remove_reference<T>::type &; 432 using const_reference = const typename std::remove_reference<T>::type &; 433 using pointer = typename std::remove_reference<T>::type *; 434 using const_pointer = const typename std::remove_reference<T>::type *; 435 436public: 437 /// Create an Expected<T> error value from the given Error. 438 Expected(Error Err) 439 : HasError(true) 440#if LLVM_ENABLE_ABI_BREAKING_CHECKS 441 // Expected is unchecked upon construction in Debug builds. 442 , Unchecked(true) 443#endif 444 { 445 assert(Err && "Cannot create Expected<T> from Error success value."); 446 new (getErrorStorage()) error_type(Err.takePayload()); 447 } 448 449 /// Forbid to convert from Error::success() implicitly, this avoids having 450 /// Expected<T> foo() { return Error::success(); } which compiles otherwise 451 /// but triggers the assertion above. 452 Expected(ErrorSuccess) = delete; 453 454 /// Create an Expected<T> success value from the given OtherT value, which 455 /// must be convertible to T. 456 template <typename OtherT> 457 Expected(OtherT &&Val, 458 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type 459 * = nullptr) 460 : HasError(false) 461#if LLVM_ENABLE_ABI_BREAKING_CHECKS 462 // Expected is unchecked upon construction in Debug builds. 463 , Unchecked(true) 464#endif 465 { 466 new (getStorage()) storage_type(std::forward<OtherT>(Val)); 467 } 468 469 /// Move construct an Expected<T> value. 470 Expected(Expected &&Other) { moveConstruct(std::move(Other)); } 471 472 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT 473 /// must be convertible to T. 474 template <class OtherT> 475 Expected(Expected<OtherT> &&Other, 476 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type 477 * = nullptr) { 478 moveConstruct(std::move(Other)); 479 } 480 481 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT 482 /// isn't convertible to T. 483 template <class OtherT> 484 explicit Expected( 485 Expected<OtherT> &&Other, 486 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * = 487 nullptr) { 488 moveConstruct(std::move(Other)); 489 } 490 491 /// Move-assign from another Expected<T>. 492 Expected &operator=(Expected &&Other) { 493 moveAssign(std::move(Other)); 494 return *this; 495 } 496 497 /// Destroy an Expected<T>. 498 ~Expected() { 499 assertIsChecked(); 500 if (!HasError) 501 getStorage()->~storage_type(); 502 else 503 getErrorStorage()->~error_type(); 504 } 505 506 /// \brief Return false if there is an error. 507 explicit operator bool() { 508#if LLVM_ENABLE_ABI_BREAKING_CHECKS 509 Unchecked = HasError; 510#endif 511 return !HasError; 512 } 513 514 /// \brief Returns a reference to the stored T value. 515 reference get() { 516 assertIsChecked(); 517 return *getStorage(); 518 } 519 520 /// \brief Returns a const reference to the stored T value. 521 const_reference get() const { 522 assertIsChecked(); 523 return const_cast<Expected<T> *>(this)->get(); 524 } 525 526 /// \brief Check that this Expected<T> is an error of type ErrT. 527 template <typename ErrT> bool errorIsA() const { 528 return HasError && (*getErrorStorage())->template isA<ErrT>(); 529 } 530 531 /// \brief Take ownership of the stored error. 532 /// After calling this the Expected<T> is in an indeterminate state that can 533 /// only be safely destructed. No further calls (beside the destructor) should 534 /// be made on the Expected<T> vaule. 535 Error takeError() { 536#if LLVM_ENABLE_ABI_BREAKING_CHECKS 537 Unchecked = false; 538#endif 539 return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); 540 } 541 542 /// \brief Returns a pointer to the stored T value. 543 pointer operator->() { 544 assertIsChecked(); 545 return toPointer(getStorage()); 546 } 547 548 /// \brief Returns a const pointer to the stored T value. 549 const_pointer operator->() const { 550 assertIsChecked(); 551 return toPointer(getStorage()); 552 } 553 554 /// \brief Returns a reference to the stored T value. 555 reference operator*() { 556 assertIsChecked(); 557 return *getStorage(); 558 } 559 560 /// \brief Returns a const reference to the stored T value. 561 const_reference operator*() const { 562 assertIsChecked(); 563 return *getStorage(); 564 } 565 566private: 567 template <class T1> 568 static bool compareThisIfSameType(const T1 &a, const T1 &b) { 569 return &a == &b; 570 } 571 572 template <class T1, class T2> 573 static bool compareThisIfSameType(const T1 &a, const T2 &b) { 574 return false; 575 } 576 577 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { 578 HasError = Other.HasError; 579#if LLVM_ENABLE_ABI_BREAKING_CHECKS 580 Unchecked = true; 581 Other.Unchecked = false; 582#endif 583 584 if (!HasError) 585 new (getStorage()) storage_type(std::move(*Other.getStorage())); 586 else 587 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); 588 } 589 590 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { 591 assertIsChecked(); 592 593 if (compareThisIfSameType(*this, Other)) 594 return; 595 596 this->~Expected(); 597 new (this) Expected(std::move(Other)); 598 } 599 600 pointer toPointer(pointer Val) { return Val; } 601 602 const_pointer toPointer(const_pointer Val) const { return Val; } 603 604 pointer toPointer(wrap *Val) { return &Val->get(); } 605 606 const_pointer toPointer(const wrap *Val) const { return &Val->get(); } 607 608 storage_type *getStorage() { 609 assert(!HasError && "Cannot get value when an error exists!"); 610 return reinterpret_cast<storage_type *>(TStorage.buffer); 611 } 612 613 const storage_type *getStorage() const { 614 assert(!HasError && "Cannot get value when an error exists!"); 615 return reinterpret_cast<const storage_type *>(TStorage.buffer); 616 } 617 618 error_type *getErrorStorage() { 619 assert(HasError && "Cannot get error when a value exists!"); 620 return reinterpret_cast<error_type *>(ErrorStorage.buffer); 621 } 622 623 const error_type *getErrorStorage() const { 624 assert(HasError && "Cannot get error when a value exists!"); 625 return reinterpret_cast<const error_type *>(ErrorStorage.buffer); 626 } 627 628 // Used by ExpectedAsOutParameter to reset the checked flag. 629 void setUnchecked() { 630#if LLVM_ENABLE_ABI_BREAKING_CHECKS 631 Unchecked = true; 632#endif 633 } 634 635 void assertIsChecked() { 636#if LLVM_ENABLE_ABI_BREAKING_CHECKS 637 if (Unchecked) { 638 dbgs() << "Expected<T> must be checked before access or destruction.\n"; 639 if (HasError) { 640 dbgs() << "Unchecked Expected<T> contained error:\n"; 641 (*getErrorStorage())->log(dbgs()); 642 } else 643 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " 644 "values in success mode must still be checked prior to being " 645 "destroyed).\n"; 646 abort(); 647 } 648#endif 649 } 650 651 union { 652 AlignedCharArrayUnion<storage_type> TStorage; 653 AlignedCharArrayUnion<error_type> ErrorStorage; 654 }; 655 bool HasError : 1; 656#if LLVM_ENABLE_ABI_BREAKING_CHECKS 657 bool Unchecked : 1; 658#endif 659}; 660 661/// Report a serious error, calling any installed error handler. See 662/// ErrorHandling.h. 663LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, 664 bool gen_crash_diag = true); 665 666/// Report a fatal error if Err is a failure value. 667/// 668/// This function can be used to wrap calls to fallible functions ONLY when it 669/// is known that the Error will always be a success value. E.g. 670/// 671/// @code{.cpp} 672/// // foo only attempts the fallible operation if DoFallibleOperation is 673/// // true. If DoFallibleOperation is false then foo always returns 674/// // Error::success(). 675/// Error foo(bool DoFallibleOperation); 676/// 677/// cantFail(foo(false)); 678/// @endcode 679inline void cantFail(Error Err, const char *Msg = nullptr) { 680 if (Err) { 681 if (!Msg) 682 Msg = "Failure value returned from cantFail wrapped call"; 683 llvm_unreachable(Msg); 684 } 685} 686 687/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and 688/// returns the contained value. 689/// 690/// This function can be used to wrap calls to fallible functions ONLY when it 691/// is known that the Error will always be a success value. E.g. 692/// 693/// @code{.cpp} 694/// // foo only attempts the fallible operation if DoFallibleOperation is 695/// // true. If DoFallibleOperation is false then foo always returns an int. 696/// Expected<int> foo(bool DoFallibleOperation); 697/// 698/// int X = cantFail(foo(false)); 699/// @endcode 700template <typename T> 701T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { 702 if (ValOrErr) 703 return std::move(*ValOrErr); 704 else { 705 if (!Msg) 706 Msg = "Failure value returned from cantFail wrapped call"; 707 llvm_unreachable(Msg); 708 } 709} 710 711/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and 712/// returns the contained reference. 713/// 714/// This function can be used to wrap calls to fallible functions ONLY when it 715/// is known that the Error will always be a success value. E.g. 716/// 717/// @code{.cpp} 718/// // foo only attempts the fallible operation if DoFallibleOperation is 719/// // true. If DoFallibleOperation is false then foo always returns a Bar&. 720/// Expected<Bar&> foo(bool DoFallibleOperation); 721/// 722/// Bar &X = cantFail(foo(false)); 723/// @endcode 724template <typename T> 725T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { 726 if (ValOrErr) 727 return *ValOrErr; 728 else { 729 if (!Msg) 730 Msg = "Failure value returned from cantFail wrapped call"; 731 llvm_unreachable(Msg); 732 } 733} 734 735/// Helper for testing applicability of, and applying, handlers for 736/// ErrorInfo types. 737template <typename HandlerT> 738class ErrorHandlerTraits 739 : public ErrorHandlerTraits<decltype( 740 &std::remove_reference<HandlerT>::type::operator())> {}; 741 742// Specialization functions of the form 'Error (const ErrT&)'. 743template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { 744public: 745 static bool appliesTo(const ErrorInfoBase &E) { 746 return E.template isA<ErrT>(); 747 } 748 749 template <typename HandlerT> 750 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 751 assert(appliesTo(*E) && "Applying incorrect handler"); 752 return H(static_cast<ErrT &>(*E)); 753 } 754}; 755 756// Specialization functions of the form 'void (const ErrT&)'. 757template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { 758public: 759 static bool appliesTo(const ErrorInfoBase &E) { 760 return E.template isA<ErrT>(); 761 } 762 763 template <typename HandlerT> 764 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 765 assert(appliesTo(*E) && "Applying incorrect handler"); 766 H(static_cast<ErrT &>(*E)); 767 return Error::success(); 768 } 769}; 770 771/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. 772template <typename ErrT> 773class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { 774public: 775 static bool appliesTo(const ErrorInfoBase &E) { 776 return E.template isA<ErrT>(); 777 } 778 779 template <typename HandlerT> 780 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 781 assert(appliesTo(*E) && "Applying incorrect handler"); 782 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); 783 return H(std::move(SubE)); 784 } 785}; 786 787/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. 788template <typename ErrT> 789class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { 790public: 791 static bool appliesTo(const ErrorInfoBase &E) { 792 return E.template isA<ErrT>(); 793 } 794 795 template <typename HandlerT> 796 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 797 assert(appliesTo(*E) && "Applying incorrect handler"); 798 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); 799 H(std::move(SubE)); 800 return Error::success(); 801 } 802}; 803 804// Specialization for member functions of the form 'RetT (const ErrT&)'. 805template <typename C, typename RetT, typename ErrT> 806class ErrorHandlerTraits<RetT (C::*)(ErrT &)> 807 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 808 809// Specialization for member functions of the form 'RetT (const ErrT&) const'. 810template <typename C, typename RetT, typename ErrT> 811class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> 812 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 813 814// Specialization for member functions of the form 'RetT (const ErrT&)'. 815template <typename C, typename RetT, typename ErrT> 816class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> 817 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 818 819// Specialization for member functions of the form 'RetT (const ErrT&) const'. 820template <typename C, typename RetT, typename ErrT> 821class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> 822 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 823 824/// Specialization for member functions of the form 825/// 'RetT (std::unique_ptr<ErrT>)'. 826template <typename C, typename RetT, typename ErrT> 827class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> 828 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; 829 830/// Specialization for member functions of the form 831/// 'RetT (std::unique_ptr<ErrT>) const'. 832template <typename C, typename RetT, typename ErrT> 833class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> 834 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; 835 836inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { 837 return Error(std::move(Payload)); 838} 839 840template <typename HandlerT, typename... HandlerTs> 841Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, 842 HandlerT &&Handler, HandlerTs &&... Handlers) { 843 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) 844 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), 845 std::move(Payload)); 846 return handleErrorImpl(std::move(Payload), 847 std::forward<HandlerTs>(Handlers)...); 848} 849 850/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any 851/// unhandled errors (or Errors returned by handlers) are re-concatenated and 852/// returned. 853/// Because this function returns an error, its result must also be checked 854/// or returned. If you intend to handle all errors use handleAllErrors 855/// (which returns void, and will abort() on unhandled errors) instead. 856template <typename... HandlerTs> 857Error handleErrors(Error E, HandlerTs &&... Hs) { 858 if (!E) 859 return Error::success(); 860 861 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); 862 863 if (Payload->isA<ErrorList>()) { 864 ErrorList &List = static_cast<ErrorList &>(*Payload); 865 Error R; 866 for (auto &P : List.Payloads) 867 R = ErrorList::join( 868 std::move(R), 869 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); 870 return R; 871 } 872 873 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); 874} 875 876/// Behaves the same as handleErrors, except that it requires that all 877/// errors be handled by the given handlers. If any unhandled error remains 878/// after the handlers have run, report_fatal_error() will be called. 879template <typename... HandlerTs> 880void handleAllErrors(Error E, HandlerTs &&... Handlers) { 881 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); 882} 883 884/// Check that E is a non-error, then drop it. 885/// If E is an error report_fatal_error will be called. 886inline void handleAllErrors(Error E) { 887 cantFail(std::move(E)); 888} 889 890/// Handle any errors (if present) in an Expected<T>, then try a recovery path. 891/// 892/// If the incoming value is a success value it is returned unmodified. If it 893/// is a failure value then it the contained error is passed to handleErrors. 894/// If handleErrors is able to handle the error then the RecoveryPath functor 895/// is called to supply the final result. If handleErrors is not able to 896/// handle all errors then the unhandled errors are returned. 897/// 898/// This utility enables the follow pattern: 899/// 900/// @code{.cpp} 901/// enum FooStrategy { Aggressive, Conservative }; 902/// Expected<Foo> foo(FooStrategy S); 903/// 904/// auto ResultOrErr = 905/// handleExpected( 906/// foo(Aggressive), 907/// []() { return foo(Conservative); }, 908/// [](AggressiveStrategyError&) { 909/// // Implicitly conusme this - we'll recover by using a conservative 910/// // strategy. 911/// }); 912/// 913/// @endcode 914template <typename T, typename RecoveryFtor, typename... HandlerTs> 915Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, 916 HandlerTs &&... Handlers) { 917 if (ValOrErr) 918 return ValOrErr; 919 920 if (auto Err = handleErrors(ValOrErr.takeError(), 921 std::forward<HandlerTs>(Handlers)...)) 922 return std::move(Err); 923 924 return RecoveryPath(); 925} 926 927/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner 928/// will be printed before the first one is logged. A newline will be printed 929/// after each error. 930/// 931/// This is useful in the base level of your program to allow clean termination 932/// (allowing clean deallocation of resources, etc.), while reporting error 933/// information to the user. 934void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner); 935 936/// Write all error messages (if any) in E to a string. The newline character 937/// is used to separate error messages. 938inline std::string toString(Error E) { 939 SmallVector<std::string, 2> Errors; 940 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { 941 Errors.push_back(EI.message()); 942 }); 943 return join(Errors.begin(), Errors.end(), "\n"); 944} 945 946/// Consume a Error without doing anything. This method should be used 947/// only where an error can be considered a reasonable and expected return 948/// value. 949/// 950/// Uses of this method are potentially indicative of design problems: If it's 951/// legitimate to do nothing while processing an "error", the error-producer 952/// might be more clearly refactored to return an Optional<T>. 953inline void consumeError(Error Err) { 954 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); 955} 956 957/// Helper for Errors used as out-parameters. 958/// 959/// This helper is for use with the Error-as-out-parameter idiom, where an error 960/// is passed to a function or method by reference, rather than being returned. 961/// In such cases it is helpful to set the checked bit on entry to the function 962/// so that the error can be written to (unchecked Errors abort on assignment) 963/// and clear the checked bit on exit so that clients cannot accidentally forget 964/// to check the result. This helper performs these actions automatically using 965/// RAII: 966/// 967/// @code{.cpp} 968/// Result foo(Error &Err) { 969/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set 970/// // <body of foo> 971/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. 972/// } 973/// @endcode 974/// 975/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be 976/// used with optional Errors (Error pointers that are allowed to be null). If 977/// ErrorAsOutParameter took an Error reference, an instance would have to be 978/// created inside every condition that verified that Error was non-null. By 979/// taking an Error pointer we can just create one instance at the top of the 980/// function. 981class ErrorAsOutParameter { 982public: 983 ErrorAsOutParameter(Error *Err) : Err(Err) { 984 // Raise the checked bit if Err is success. 985 if (Err) 986 (void)!!*Err; 987 } 988 989 ~ErrorAsOutParameter() { 990 // Clear the checked bit. 991 if (Err && !*Err) 992 *Err = Error::success(); 993 } 994 995private: 996 Error *Err; 997}; 998 999/// Helper for Expected<T>s used as out-parameters. 1000/// 1001/// See ErrorAsOutParameter. 1002template <typename T> 1003class ExpectedAsOutParameter { 1004public: 1005 ExpectedAsOutParameter(Expected<T> *ValOrErr) 1006 : ValOrErr(ValOrErr) { 1007 if (ValOrErr) 1008 (void)!!*ValOrErr; 1009 } 1010 1011 ~ExpectedAsOutParameter() { 1012 if (ValOrErr) 1013 ValOrErr->setUnchecked(); 1014 } 1015 1016private: 1017 Expected<T> *ValOrErr; 1018}; 1019 1020/// This class wraps a std::error_code in a Error. 1021/// 1022/// This is useful if you're writing an interface that returns a Error 1023/// (or Expected) and you want to call code that still returns 1024/// std::error_codes. 1025class ECError : public ErrorInfo<ECError> { 1026 friend Error errorCodeToError(std::error_code); 1027 1028public: 1029 void setErrorCode(std::error_code EC) { this->EC = EC; } 1030 std::error_code convertToErrorCode() const override { return EC; } 1031 void log(raw_ostream &OS) const override { OS << EC.message(); } 1032 1033 // Used by ErrorInfo::classID. 1034 static char ID; 1035 1036protected: 1037 ECError() = default; 1038 ECError(std::error_code EC) : EC(EC) {} 1039 1040 std::error_code EC; 1041}; 1042 1043/// The value returned by this function can be returned from convertToErrorCode 1044/// for Error values where no sensible translation to std::error_code exists. 1045/// It should only be used in this situation, and should never be used where a 1046/// sensible conversion to std::error_code is available, as attempts to convert 1047/// to/from this error will result in a fatal error. (i.e. it is a programmatic 1048///error to try to convert such a value). 1049std::error_code inconvertibleErrorCode(); 1050 1051/// Helper for converting an std::error_code to a Error. 1052Error errorCodeToError(std::error_code EC); 1053 1054/// Helper for converting an ECError to a std::error_code. 1055/// 1056/// This method requires that Err be Error() or an ECError, otherwise it 1057/// will trigger a call to abort(). 1058std::error_code errorToErrorCode(Error Err); 1059 1060/// Convert an ErrorOr<T> to an Expected<T>. 1061template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { 1062 if (auto EC = EO.getError()) 1063 return errorCodeToError(EC); 1064 return std::move(*EO); 1065} 1066 1067/// Convert an Expected<T> to an ErrorOr<T>. 1068template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { 1069 if (auto Err = E.takeError()) 1070 return errorToErrorCode(std::move(Err)); 1071 return std::move(*E); 1072} 1073 1074/// This class wraps a string in an Error. 1075/// 1076/// StringError is useful in cases where the client is not expected to be able 1077/// to consume the specific error message programmatically (for example, if the 1078/// error message is to be presented to the user). 1079class StringError : public ErrorInfo<StringError> { 1080public: 1081 static char ID; 1082 1083 StringError(const Twine &S, std::error_code EC); 1084 1085 void log(raw_ostream &OS) const override; 1086 std::error_code convertToErrorCode() const override; 1087 1088 const std::string &getMessage() const { return Msg; } 1089 1090private: 1091 std::string Msg; 1092 std::error_code EC; 1093}; 1094 1095/// Helper for check-and-exit error handling. 1096/// 1097/// For tool use only. NOT FOR USE IN LIBRARY CODE. 1098/// 1099class ExitOnError { 1100public: 1101 /// Create an error on exit helper. 1102 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) 1103 : Banner(std::move(Banner)), 1104 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} 1105 1106 /// Set the banner string for any errors caught by operator(). 1107 void setBanner(std::string Banner) { this->Banner = std::move(Banner); } 1108 1109 /// Set the exit-code mapper function. 1110 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { 1111 this->GetExitCode = std::move(GetExitCode); 1112 } 1113 1114 /// Check Err. If it's in a failure state log the error(s) and exit. 1115 void operator()(Error Err) const { checkError(std::move(Err)); } 1116 1117 /// Check E. If it's in a success state then return the contained value. If 1118 /// it's in a failure state log the error(s) and exit. 1119 template <typename T> T operator()(Expected<T> &&E) const { 1120 checkError(E.takeError()); 1121 return std::move(*E); 1122 } 1123 1124 /// Check E. If it's in a success state then return the contained reference. If 1125 /// it's in a failure state log the error(s) and exit. 1126 template <typename T> T& operator()(Expected<T&> &&E) const { 1127 checkError(E.takeError()); 1128 return *E; 1129 } 1130 1131private: 1132 void checkError(Error Err) const { 1133 if (Err) { 1134 int ExitCode = GetExitCode(Err); 1135 logAllUnhandledErrors(std::move(Err), errs(), Banner); 1136 exit(ExitCode); 1137 } 1138 } 1139 1140 std::string Banner; 1141 std::function<int(const Error &)> GetExitCode; 1142}; 1143 1144} // end namespace llvm 1145 1146#endif // LLVM_SUPPORT_ERROR_H 1147