Error.h revision 344779
1321369Sdim//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// 2303231Sdim// 3303231Sdim// The LLVM Compiler Infrastructure 4303231Sdim// 5303231Sdim// This file is distributed under the University of Illinois Open Source 6303231Sdim// License. See LICENSE.TXT for details. 7303231Sdim// 8303231Sdim//===----------------------------------------------------------------------===// 9303231Sdim// 10303231Sdim// This file defines an API used to report recoverable errors. 11303231Sdim// 12303231Sdim//===----------------------------------------------------------------------===// 13303231Sdim 14303231Sdim#ifndef LLVM_SUPPORT_ERROR_H 15303231Sdim#define LLVM_SUPPORT_ERROR_H 16303231Sdim 17344779Sdim#include "llvm-c/Error.h" 18344779Sdim#include "llvm/ADT/STLExtras.h" 19314564Sdim#include "llvm/ADT/SmallVector.h" 20303231Sdim#include "llvm/ADT/StringExtras.h" 21303231Sdim#include "llvm/ADT/Twine.h" 22314564Sdim#include "llvm/Config/abi-breaking.h" 23314564Sdim#include "llvm/Support/AlignOf.h" 24314564Sdim#include "llvm/Support/Compiler.h" 25303231Sdim#include "llvm/Support/Debug.h" 26321369Sdim#include "llvm/Support/ErrorHandling.h" 27303231Sdim#include "llvm/Support/ErrorOr.h" 28341825Sdim#include "llvm/Support/Format.h" 29303231Sdim#include "llvm/Support/raw_ostream.h" 30314564Sdim#include <algorithm> 31314564Sdim#include <cassert> 32314564Sdim#include <cstdint> 33314564Sdim#include <cstdlib> 34314564Sdim#include <functional> 35314564Sdim#include <memory> 36314564Sdim#include <new> 37314564Sdim#include <string> 38314564Sdim#include <system_error> 39314564Sdim#include <type_traits> 40314564Sdim#include <utility> 41303231Sdim#include <vector> 42303231Sdim 43303231Sdimnamespace llvm { 44303231Sdim 45314564Sdimclass ErrorSuccess; 46303231Sdim 47303231Sdim/// Base class for error info classes. Do not extend this directly: Extend 48303231Sdim/// the ErrorInfo template subclass instead. 49303231Sdimclass ErrorInfoBase { 50303231Sdimpublic: 51314564Sdim virtual ~ErrorInfoBase() = default; 52303231Sdim 53303231Sdim /// Print an error message to an output stream. 54303231Sdim virtual void log(raw_ostream &OS) const = 0; 55303231Sdim 56303231Sdim /// Return the error message as a string. 57303231Sdim virtual std::string message() const { 58303231Sdim std::string Msg; 59303231Sdim raw_string_ostream OS(Msg); 60303231Sdim log(OS); 61303231Sdim return OS.str(); 62303231Sdim } 63303231Sdim 64303231Sdim /// Convert this error to a std::error_code. 65303231Sdim /// 66303231Sdim /// This is a temporary crutch to enable interaction with code still 67303231Sdim /// using std::error_code. It will be removed in the future. 68303231Sdim virtual std::error_code convertToErrorCode() const = 0; 69303231Sdim 70321369Sdim // Returns the class ID for this type. 71321369Sdim static const void *classID() { return &ID; } 72321369Sdim 73321369Sdim // Returns the class ID for the dynamic type of this ErrorInfoBase instance. 74321369Sdim virtual const void *dynamicClassID() const = 0; 75321369Sdim 76303231Sdim // Check whether this instance is a subclass of the class identified by 77303231Sdim // ClassID. 78303231Sdim virtual bool isA(const void *const ClassID) const { 79303231Sdim return ClassID == classID(); 80303231Sdim } 81303231Sdim 82303231Sdim // Check whether this instance is a subclass of ErrorInfoT. 83303231Sdim template <typename ErrorInfoT> bool isA() const { 84303231Sdim return isA(ErrorInfoT::classID()); 85303231Sdim } 86303231Sdim 87303231Sdimprivate: 88303231Sdim virtual void anchor(); 89314564Sdim 90303231Sdim static char ID; 91303231Sdim}; 92303231Sdim 93303231Sdim/// Lightweight error class with error context and mandatory checking. 94303231Sdim/// 95303231Sdim/// Instances of this class wrap a ErrorInfoBase pointer. Failure states 96303231Sdim/// are represented by setting the pointer to a ErrorInfoBase subclass 97303231Sdim/// instance containing information describing the failure. Success is 98303231Sdim/// represented by a null pointer value. 99303231Sdim/// 100303231Sdim/// Instances of Error also contains a 'Checked' flag, which must be set 101303231Sdim/// before the destructor is called, otherwise the destructor will trigger a 102303231Sdim/// runtime error. This enforces at runtime the requirement that all Error 103303231Sdim/// instances be checked or returned to the caller. 104303231Sdim/// 105303231Sdim/// There are two ways to set the checked flag, depending on what state the 106303231Sdim/// Error instance is in. For Error instances indicating success, it 107303231Sdim/// is sufficient to invoke the boolean conversion operator. E.g.: 108303231Sdim/// 109314564Sdim/// @code{.cpp} 110303231Sdim/// Error foo(<...>); 111303231Sdim/// 112303231Sdim/// if (auto E = foo(<...>)) 113303231Sdim/// return E; // <- Return E if it is in the error state. 114303231Sdim/// // We have verified that E was in the success state. It can now be safely 115303231Sdim/// // destroyed. 116314564Sdim/// @endcode 117303231Sdim/// 118303231Sdim/// A success value *can not* be dropped. For example, just calling 'foo(<...>)' 119303231Sdim/// without testing the return value will raise a runtime error, even if foo 120303231Sdim/// returns success. 121303231Sdim/// 122303231Sdim/// For Error instances representing failure, you must use either the 123303231Sdim/// handleErrors or handleAllErrors function with a typed handler. E.g.: 124303231Sdim/// 125314564Sdim/// @code{.cpp} 126303231Sdim/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { 127303231Sdim/// // Custom error info. 128303231Sdim/// }; 129303231Sdim/// 130303231Sdim/// Error foo(<...>) { return make_error<MyErrorInfo>(...); } 131303231Sdim/// 132303231Sdim/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. 133303231Sdim/// auto NewE = 134303231Sdim/// handleErrors(E, 135303231Sdim/// [](const MyErrorInfo &M) { 136303231Sdim/// // Deal with the error. 137303231Sdim/// }, 138303231Sdim/// [](std::unique_ptr<OtherError> M) -> Error { 139303231Sdim/// if (canHandle(*M)) { 140303231Sdim/// // handle error. 141303231Sdim/// return Error::success(); 142303231Sdim/// } 143303231Sdim/// // Couldn't handle this error instance. Pass it up the stack. 144303231Sdim/// return Error(std::move(M)); 145303231Sdim/// ); 146303231Sdim/// // Note - we must check or return NewE in case any of the handlers 147303231Sdim/// // returned a new error. 148314564Sdim/// @endcode 149303231Sdim/// 150303231Sdim/// The handleAllErrors function is identical to handleErrors, except 151303231Sdim/// that it has a void return type, and requires all errors to be handled and 152303231Sdim/// no new errors be returned. It prevents errors (assuming they can all be 153303231Sdim/// handled) from having to be bubbled all the way to the top-level. 154303231Sdim/// 155303231Sdim/// *All* Error instances must be checked before destruction, even if 156303231Sdim/// they're moved-assigned or constructed from Success values that have already 157303231Sdim/// been checked. This enforces checking through all levels of the call stack. 158314564Sdimclass LLVM_NODISCARD Error { 159344779Sdim // Both ErrorList and FileError need to be able to yank ErrorInfoBase 160344779Sdim // pointers out of this class to add to the error list. 161303231Sdim friend class ErrorList; 162344779Sdim friend class FileError; 163303231Sdim 164303231Sdim // handleErrors needs to be able to set the Checked flag. 165303231Sdim template <typename... HandlerTs> 166303231Sdim friend Error handleErrors(Error E, HandlerTs &&... Handlers); 167303231Sdim 168303231Sdim // Expected<T> needs to be able to steal the payload when constructed from an 169303231Sdim // error. 170314564Sdim template <typename T> friend class Expected; 171303231Sdim 172344779Sdim // wrap needs to be able to steal the payload. 173344779Sdim friend LLVMErrorRef wrap(Error); 174344779Sdim 175314564Sdimprotected: 176303231Sdim /// Create a success value. Prefer using 'Error::success()' for readability 177321369Sdim Error() { 178303231Sdim setPtr(nullptr); 179303231Sdim setChecked(false); 180303231Sdim } 181303231Sdim 182314564Sdimpublic: 183314564Sdim /// Create a success value. 184314564Sdim static ErrorSuccess success(); 185303231Sdim 186303231Sdim // Errors are not copy-constructable. 187303231Sdim Error(const Error &Other) = delete; 188303231Sdim 189303231Sdim /// Move-construct an error value. The newly constructed error is considered 190303231Sdim /// unchecked, even if the source error had been checked. The original error 191303231Sdim /// becomes a checked Success value, regardless of its original state. 192321369Sdim Error(Error &&Other) { 193303231Sdim setChecked(true); 194303231Sdim *this = std::move(Other); 195303231Sdim } 196303231Sdim 197303231Sdim /// Create an error value. Prefer using the 'make_error' function, but 198303231Sdim /// this constructor can be useful when "re-throwing" errors from handlers. 199303231Sdim Error(std::unique_ptr<ErrorInfoBase> Payload) { 200303231Sdim setPtr(Payload.release()); 201303231Sdim setChecked(false); 202303231Sdim } 203303231Sdim 204303231Sdim // Errors are not copy-assignable. 205303231Sdim Error &operator=(const Error &Other) = delete; 206303231Sdim 207303231Sdim /// Move-assign an error value. The current error must represent success, you 208303231Sdim /// you cannot overwrite an unhandled error. The current error is then 209303231Sdim /// considered unchecked. The source error becomes a checked success value, 210303231Sdim /// regardless of its original state. 211303231Sdim Error &operator=(Error &&Other) { 212303231Sdim // Don't allow overwriting of unchecked values. 213303231Sdim assertIsChecked(); 214303231Sdim setPtr(Other.getPtr()); 215303231Sdim 216303231Sdim // This Error is unchecked, even if the source error was checked. 217303231Sdim setChecked(false); 218303231Sdim 219303231Sdim // Null out Other's payload and set its checked bit. 220303231Sdim Other.setPtr(nullptr); 221303231Sdim Other.setChecked(true); 222303231Sdim 223303231Sdim return *this; 224303231Sdim } 225303231Sdim 226303231Sdim /// Destroy a Error. Fails with a call to abort() if the error is 227303231Sdim /// unchecked. 228303231Sdim ~Error() { 229303231Sdim assertIsChecked(); 230303231Sdim delete getPtr(); 231303231Sdim } 232303231Sdim 233303231Sdim /// Bool conversion. Returns true if this Error is in a failure state, 234303231Sdim /// and false if it is in an accept state. If the error is in a Success state 235303231Sdim /// it will be considered checked. 236303231Sdim explicit operator bool() { 237303231Sdim setChecked(getPtr() == nullptr); 238303231Sdim return getPtr() != nullptr; 239303231Sdim } 240303231Sdim 241303231Sdim /// Check whether one error is a subclass of another. 242303231Sdim template <typename ErrT> bool isA() const { 243303231Sdim return getPtr() && getPtr()->isA(ErrT::classID()); 244303231Sdim } 245303231Sdim 246321369Sdim /// Returns the dynamic class id of this error, or null if this is a success 247321369Sdim /// value. 248321369Sdim const void* dynamicClassID() const { 249321369Sdim if (!getPtr()) 250321369Sdim return nullptr; 251321369Sdim return getPtr()->dynamicClassID(); 252321369Sdim } 253321369Sdim 254303231Sdimprivate: 255327952Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 256327952Sdim // assertIsChecked() happens very frequently, but under normal circumstances 257327952Sdim // is supposed to be a no-op. So we want it to be inlined, but having a bunch 258327952Sdim // of debug prints can cause the function to be too large for inlining. So 259327952Sdim // it's important that we define this function out of line so that it can't be 260327952Sdim // inlined. 261327952Sdim LLVM_ATTRIBUTE_NORETURN 262327952Sdim void fatalUncheckedError() const; 263327952Sdim#endif 264327952Sdim 265303231Sdim void assertIsChecked() { 266314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 267327952Sdim if (LLVM_UNLIKELY(!getChecked() || getPtr())) 268327952Sdim fatalUncheckedError(); 269303231Sdim#endif 270303231Sdim } 271303231Sdim 272303231Sdim ErrorInfoBase *getPtr() const { 273314564Sdim return reinterpret_cast<ErrorInfoBase*>( 274314564Sdim reinterpret_cast<uintptr_t>(Payload) & 275314564Sdim ~static_cast<uintptr_t>(0x1)); 276303231Sdim } 277303231Sdim 278303231Sdim void setPtr(ErrorInfoBase *EI) { 279314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 280314564Sdim Payload = reinterpret_cast<ErrorInfoBase*>( 281314564Sdim (reinterpret_cast<uintptr_t>(EI) & 282314564Sdim ~static_cast<uintptr_t>(0x1)) | 283314564Sdim (reinterpret_cast<uintptr_t>(Payload) & 0x1)); 284303231Sdim#else 285303231Sdim Payload = EI; 286303231Sdim#endif 287303231Sdim } 288303231Sdim 289303231Sdim bool getChecked() const { 290314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 291314564Sdim return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; 292303231Sdim#else 293303231Sdim return true; 294303231Sdim#endif 295303231Sdim } 296303231Sdim 297303231Sdim void setChecked(bool V) { 298314564Sdim Payload = reinterpret_cast<ErrorInfoBase*>( 299314564Sdim (reinterpret_cast<uintptr_t>(Payload) & 300314564Sdim ~static_cast<uintptr_t>(0x1)) | 301314564Sdim (V ? 0 : 1)); 302303231Sdim } 303303231Sdim 304303231Sdim std::unique_ptr<ErrorInfoBase> takePayload() { 305303231Sdim std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); 306303231Sdim setPtr(nullptr); 307303231Sdim setChecked(true); 308303231Sdim return Tmp; 309303231Sdim } 310303231Sdim 311341825Sdim friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { 312341825Sdim if (auto P = E.getPtr()) 313341825Sdim P->log(OS); 314341825Sdim else 315341825Sdim OS << "success"; 316341825Sdim return OS; 317341825Sdim } 318341825Sdim 319321369Sdim ErrorInfoBase *Payload = nullptr; 320303231Sdim}; 321303231Sdim 322314564Sdim/// Subclass of Error for the sole purpose of identifying the success path in 323314564Sdim/// the type system. This allows to catch invalid conversion to Expected<T> at 324314564Sdim/// compile time. 325344779Sdimclass ErrorSuccess final : public Error {}; 326314564Sdim 327314564Sdiminline ErrorSuccess Error::success() { return ErrorSuccess(); } 328314564Sdim 329303231Sdim/// Make a Error instance representing failure using the given error info 330303231Sdim/// type. 331303231Sdimtemplate <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { 332303231Sdim return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); 333303231Sdim} 334303231Sdim 335303231Sdim/// Base class for user error types. Users should declare their error types 336303231Sdim/// like: 337303231Sdim/// 338303231Sdim/// class MyError : public ErrorInfo<MyError> { 339303231Sdim/// .... 340303231Sdim/// }; 341303231Sdim/// 342303231Sdim/// This class provides an implementation of the ErrorInfoBase::kind 343303231Sdim/// method, which is used by the Error RTTI system. 344303231Sdimtemplate <typename ThisErrT, typename ParentErrT = ErrorInfoBase> 345303231Sdimclass ErrorInfo : public ParentErrT { 346303231Sdimpublic: 347344779Sdim using ParentErrT::ParentErrT; // inherit constructors 348344779Sdim 349321369Sdim static const void *classID() { return &ThisErrT::ID; } 350321369Sdim 351321369Sdim const void *dynamicClassID() const override { return &ThisErrT::ID; } 352321369Sdim 353303231Sdim bool isA(const void *const ClassID) const override { 354303231Sdim return ClassID == classID() || ParentErrT::isA(ClassID); 355303231Sdim } 356303231Sdim}; 357303231Sdim 358303231Sdim/// Special ErrorInfo subclass representing a list of ErrorInfos. 359303231Sdim/// Instances of this class are constructed by joinError. 360303231Sdimclass ErrorList final : public ErrorInfo<ErrorList> { 361303231Sdim // handleErrors needs to be able to iterate the payload list of an 362303231Sdim // ErrorList. 363303231Sdim template <typename... HandlerTs> 364303231Sdim friend Error handleErrors(Error E, HandlerTs &&... Handlers); 365303231Sdim 366303231Sdim // joinErrors is implemented in terms of join. 367303231Sdim friend Error joinErrors(Error, Error); 368303231Sdim 369303231Sdimpublic: 370303231Sdim void log(raw_ostream &OS) const override { 371303231Sdim OS << "Multiple errors:\n"; 372303231Sdim for (auto &ErrPayload : Payloads) { 373303231Sdim ErrPayload->log(OS); 374303231Sdim OS << "\n"; 375303231Sdim } 376303231Sdim } 377303231Sdim 378303231Sdim std::error_code convertToErrorCode() const override; 379303231Sdim 380303231Sdim // Used by ErrorInfo::classID. 381303231Sdim static char ID; 382303231Sdim 383303231Sdimprivate: 384303231Sdim ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, 385303231Sdim std::unique_ptr<ErrorInfoBase> Payload2) { 386303231Sdim assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && 387303231Sdim "ErrorList constructor payloads should be singleton errors"); 388303231Sdim Payloads.push_back(std::move(Payload1)); 389303231Sdim Payloads.push_back(std::move(Payload2)); 390303231Sdim } 391303231Sdim 392303231Sdim static Error join(Error E1, Error E2) { 393303231Sdim if (!E1) 394303231Sdim return E2; 395303231Sdim if (!E2) 396303231Sdim return E1; 397303231Sdim if (E1.isA<ErrorList>()) { 398303231Sdim auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); 399303231Sdim if (E2.isA<ErrorList>()) { 400303231Sdim auto E2Payload = E2.takePayload(); 401303231Sdim auto &E2List = static_cast<ErrorList &>(*E2Payload); 402303231Sdim for (auto &Payload : E2List.Payloads) 403303231Sdim E1List.Payloads.push_back(std::move(Payload)); 404303231Sdim } else 405303231Sdim E1List.Payloads.push_back(E2.takePayload()); 406303231Sdim 407303231Sdim return E1; 408303231Sdim } 409303231Sdim if (E2.isA<ErrorList>()) { 410303231Sdim auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); 411303231Sdim E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); 412303231Sdim return E2; 413303231Sdim } 414303231Sdim return Error(std::unique_ptr<ErrorList>( 415303231Sdim new ErrorList(E1.takePayload(), E2.takePayload()))); 416303231Sdim } 417303231Sdim 418303231Sdim std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; 419303231Sdim}; 420303231Sdim 421303231Sdim/// Concatenate errors. The resulting Error is unchecked, and contains the 422303231Sdim/// ErrorInfo(s), if any, contained in E1, followed by the 423303231Sdim/// ErrorInfo(s), if any, contained in E2. 424303231Sdiminline Error joinErrors(Error E1, Error E2) { 425303231Sdim return ErrorList::join(std::move(E1), std::move(E2)); 426303231Sdim} 427303231Sdim 428303231Sdim/// Tagged union holding either a T or a Error. 429303231Sdim/// 430303231Sdim/// This class parallels ErrorOr, but replaces error_code with Error. Since 431303231Sdim/// Error cannot be copied, this class replaces getError() with 432303231Sdim/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the 433303231Sdim/// error class type. 434314564Sdimtemplate <class T> class LLVM_NODISCARD Expected { 435321369Sdim template <class T1> friend class ExpectedAsOutParameter; 436303231Sdim template <class OtherT> friend class Expected; 437321369Sdim 438303231Sdim static const bool isRef = std::is_reference<T>::value; 439303231Sdim 440341825Sdim using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>; 441303231Sdim 442321369Sdim using error_type = std::unique_ptr<ErrorInfoBase>; 443321369Sdim 444303231Sdimpublic: 445321369Sdim using storage_type = typename std::conditional<isRef, wrap, T>::type; 446321369Sdim using value_type = T; 447303231Sdim 448303231Sdimprivate: 449321369Sdim using reference = typename std::remove_reference<T>::type &; 450321369Sdim using const_reference = const typename std::remove_reference<T>::type &; 451321369Sdim using pointer = typename std::remove_reference<T>::type *; 452321369Sdim using const_pointer = const typename std::remove_reference<T>::type *; 453303231Sdim 454303231Sdimpublic: 455303231Sdim /// Create an Expected<T> error value from the given Error. 456303231Sdim Expected(Error Err) 457303231Sdim : HasError(true) 458314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 459314564Sdim // Expected is unchecked upon construction in Debug builds. 460314564Sdim , Unchecked(true) 461303231Sdim#endif 462303231Sdim { 463303231Sdim assert(Err && "Cannot create Expected<T> from Error success value."); 464314564Sdim new (getErrorStorage()) error_type(Err.takePayload()); 465303231Sdim } 466303231Sdim 467314564Sdim /// Forbid to convert from Error::success() implicitly, this avoids having 468314564Sdim /// Expected<T> foo() { return Error::success(); } which compiles otherwise 469314564Sdim /// but triggers the assertion above. 470314564Sdim Expected(ErrorSuccess) = delete; 471314564Sdim 472303231Sdim /// Create an Expected<T> success value from the given OtherT value, which 473303231Sdim /// must be convertible to T. 474303231Sdim template <typename OtherT> 475303231Sdim Expected(OtherT &&Val, 476303231Sdim typename std::enable_if<std::is_convertible<OtherT, T>::value>::type 477303231Sdim * = nullptr) 478303231Sdim : HasError(false) 479314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 480314564Sdim // Expected is unchecked upon construction in Debug builds. 481314564Sdim , Unchecked(true) 482303231Sdim#endif 483303231Sdim { 484303231Sdim new (getStorage()) storage_type(std::forward<OtherT>(Val)); 485303231Sdim } 486303231Sdim 487303231Sdim /// Move construct an Expected<T> value. 488303231Sdim Expected(Expected &&Other) { moveConstruct(std::move(Other)); } 489303231Sdim 490303231Sdim /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT 491303231Sdim /// must be convertible to T. 492303231Sdim template <class OtherT> 493303231Sdim Expected(Expected<OtherT> &&Other, 494303231Sdim typename std::enable_if<std::is_convertible<OtherT, T>::value>::type 495303231Sdim * = nullptr) { 496303231Sdim moveConstruct(std::move(Other)); 497303231Sdim } 498303231Sdim 499303231Sdim /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT 500303231Sdim /// isn't convertible to T. 501303231Sdim template <class OtherT> 502303231Sdim explicit Expected( 503303231Sdim Expected<OtherT> &&Other, 504303231Sdim typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * = 505303231Sdim nullptr) { 506303231Sdim moveConstruct(std::move(Other)); 507303231Sdim } 508303231Sdim 509303231Sdim /// Move-assign from another Expected<T>. 510303231Sdim Expected &operator=(Expected &&Other) { 511303231Sdim moveAssign(std::move(Other)); 512303231Sdim return *this; 513303231Sdim } 514303231Sdim 515303231Sdim /// Destroy an Expected<T>. 516303231Sdim ~Expected() { 517303231Sdim assertIsChecked(); 518303231Sdim if (!HasError) 519303231Sdim getStorage()->~storage_type(); 520303231Sdim else 521303231Sdim getErrorStorage()->~error_type(); 522303231Sdim } 523303231Sdim 524341825Sdim /// Return false if there is an error. 525303231Sdim explicit operator bool() { 526314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 527314564Sdim Unchecked = HasError; 528303231Sdim#endif 529303231Sdim return !HasError; 530303231Sdim } 531303231Sdim 532341825Sdim /// Returns a reference to the stored T value. 533303231Sdim reference get() { 534303231Sdim assertIsChecked(); 535303231Sdim return *getStorage(); 536303231Sdim } 537303231Sdim 538341825Sdim /// Returns a const reference to the stored T value. 539303231Sdim const_reference get() const { 540303231Sdim assertIsChecked(); 541303231Sdim return const_cast<Expected<T> *>(this)->get(); 542303231Sdim } 543303231Sdim 544341825Sdim /// Check that this Expected<T> is an error of type ErrT. 545303231Sdim template <typename ErrT> bool errorIsA() const { 546321369Sdim return HasError && (*getErrorStorage())->template isA<ErrT>(); 547303231Sdim } 548303231Sdim 549341825Sdim /// Take ownership of the stored error. 550303231Sdim /// After calling this the Expected<T> is in an indeterminate state that can 551303231Sdim /// only be safely destructed. No further calls (beside the destructor) should 552303231Sdim /// be made on the Expected<T> vaule. 553303231Sdim Error takeError() { 554314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 555314564Sdim Unchecked = false; 556303231Sdim#endif 557303231Sdim return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); 558303231Sdim } 559303231Sdim 560341825Sdim /// Returns a pointer to the stored T value. 561303231Sdim pointer operator->() { 562303231Sdim assertIsChecked(); 563303231Sdim return toPointer(getStorage()); 564303231Sdim } 565303231Sdim 566341825Sdim /// Returns a const pointer to the stored T value. 567303231Sdim const_pointer operator->() const { 568303231Sdim assertIsChecked(); 569303231Sdim return toPointer(getStorage()); 570303231Sdim } 571303231Sdim 572341825Sdim /// Returns a reference to the stored T value. 573303231Sdim reference operator*() { 574303231Sdim assertIsChecked(); 575303231Sdim return *getStorage(); 576303231Sdim } 577303231Sdim 578341825Sdim /// Returns a const reference to the stored T value. 579303231Sdim const_reference operator*() const { 580303231Sdim assertIsChecked(); 581303231Sdim return *getStorage(); 582303231Sdim } 583303231Sdim 584303231Sdimprivate: 585303231Sdim template <class T1> 586303231Sdim static bool compareThisIfSameType(const T1 &a, const T1 &b) { 587303231Sdim return &a == &b; 588303231Sdim } 589303231Sdim 590303231Sdim template <class T1, class T2> 591303231Sdim static bool compareThisIfSameType(const T1 &a, const T2 &b) { 592303231Sdim return false; 593303231Sdim } 594303231Sdim 595303231Sdim template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { 596303231Sdim HasError = Other.HasError; 597314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 598314564Sdim Unchecked = true; 599314564Sdim Other.Unchecked = false; 600303231Sdim#endif 601303231Sdim 602303231Sdim if (!HasError) 603303231Sdim new (getStorage()) storage_type(std::move(*Other.getStorage())); 604303231Sdim else 605303231Sdim new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); 606303231Sdim } 607303231Sdim 608303231Sdim template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { 609303231Sdim assertIsChecked(); 610303231Sdim 611303231Sdim if (compareThisIfSameType(*this, Other)) 612303231Sdim return; 613303231Sdim 614303231Sdim this->~Expected(); 615303231Sdim new (this) Expected(std::move(Other)); 616303231Sdim } 617303231Sdim 618303231Sdim pointer toPointer(pointer Val) { return Val; } 619303231Sdim 620303231Sdim const_pointer toPointer(const_pointer Val) const { return Val; } 621303231Sdim 622303231Sdim pointer toPointer(wrap *Val) { return &Val->get(); } 623303231Sdim 624303231Sdim const_pointer toPointer(const wrap *Val) const { return &Val->get(); } 625303231Sdim 626303231Sdim storage_type *getStorage() { 627303231Sdim assert(!HasError && "Cannot get value when an error exists!"); 628303231Sdim return reinterpret_cast<storage_type *>(TStorage.buffer); 629303231Sdim } 630303231Sdim 631303231Sdim const storage_type *getStorage() const { 632303231Sdim assert(!HasError && "Cannot get value when an error exists!"); 633303231Sdim return reinterpret_cast<const storage_type *>(TStorage.buffer); 634303231Sdim } 635303231Sdim 636303231Sdim error_type *getErrorStorage() { 637303231Sdim assert(HasError && "Cannot get error when a value exists!"); 638303231Sdim return reinterpret_cast<error_type *>(ErrorStorage.buffer); 639303231Sdim } 640303231Sdim 641321369Sdim const error_type *getErrorStorage() const { 642321369Sdim assert(HasError && "Cannot get error when a value exists!"); 643321369Sdim return reinterpret_cast<const error_type *>(ErrorStorage.buffer); 644321369Sdim } 645321369Sdim 646321369Sdim // Used by ExpectedAsOutParameter to reset the checked flag. 647321369Sdim void setUnchecked() { 648321369Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 649321369Sdim Unchecked = true; 650321369Sdim#endif 651321369Sdim } 652321369Sdim 653327952Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 654327952Sdim LLVM_ATTRIBUTE_NORETURN 655327952Sdim LLVM_ATTRIBUTE_NOINLINE 656327952Sdim void fatalUncheckedExpected() const { 657327952Sdim dbgs() << "Expected<T> must be checked before access or destruction.\n"; 658327952Sdim if (HasError) { 659327952Sdim dbgs() << "Unchecked Expected<T> contained error:\n"; 660327952Sdim (*getErrorStorage())->log(dbgs()); 661327952Sdim } else 662327952Sdim dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " 663327952Sdim "values in success mode must still be checked prior to being " 664327952Sdim "destroyed).\n"; 665327952Sdim abort(); 666327952Sdim } 667327952Sdim#endif 668327952Sdim 669303231Sdim void assertIsChecked() { 670314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 671327952Sdim if (LLVM_UNLIKELY(Unchecked)) 672327952Sdim fatalUncheckedExpected(); 673303231Sdim#endif 674303231Sdim } 675303231Sdim 676303231Sdim union { 677303231Sdim AlignedCharArrayUnion<storage_type> TStorage; 678303231Sdim AlignedCharArrayUnion<error_type> ErrorStorage; 679303231Sdim }; 680303231Sdim bool HasError : 1; 681314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 682314564Sdim bool Unchecked : 1; 683303231Sdim#endif 684303231Sdim}; 685303231Sdim 686327952Sdim/// Report a serious error, calling any installed error handler. See 687327952Sdim/// ErrorHandling.h. 688327952SdimLLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, 689327952Sdim bool gen_crash_diag = true); 690327952Sdim 691327952Sdim/// Report a fatal error if Err is a failure value. 692327952Sdim/// 693327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it 694327952Sdim/// is known that the Error will always be a success value. E.g. 695327952Sdim/// 696327952Sdim/// @code{.cpp} 697327952Sdim/// // foo only attempts the fallible operation if DoFallibleOperation is 698327952Sdim/// // true. If DoFallibleOperation is false then foo always returns 699327952Sdim/// // Error::success(). 700327952Sdim/// Error foo(bool DoFallibleOperation); 701327952Sdim/// 702327952Sdim/// cantFail(foo(false)); 703327952Sdim/// @endcode 704327952Sdiminline void cantFail(Error Err, const char *Msg = nullptr) { 705327952Sdim if (Err) { 706327952Sdim if (!Msg) 707327952Sdim Msg = "Failure value returned from cantFail wrapped call"; 708327952Sdim llvm_unreachable(Msg); 709327952Sdim } 710327952Sdim} 711327952Sdim 712327952Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and 713327952Sdim/// returns the contained value. 714327952Sdim/// 715327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it 716327952Sdim/// is known that the Error will always be a success value. E.g. 717327952Sdim/// 718327952Sdim/// @code{.cpp} 719327952Sdim/// // foo only attempts the fallible operation if DoFallibleOperation is 720327952Sdim/// // true. If DoFallibleOperation is false then foo always returns an int. 721327952Sdim/// Expected<int> foo(bool DoFallibleOperation); 722327952Sdim/// 723327952Sdim/// int X = cantFail(foo(false)); 724327952Sdim/// @endcode 725327952Sdimtemplate <typename T> 726327952SdimT cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { 727327952Sdim if (ValOrErr) 728327952Sdim return std::move(*ValOrErr); 729327952Sdim else { 730327952Sdim if (!Msg) 731327952Sdim Msg = "Failure value returned from cantFail wrapped call"; 732327952Sdim llvm_unreachable(Msg); 733327952Sdim } 734327952Sdim} 735327952Sdim 736327952Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and 737327952Sdim/// returns the contained reference. 738327952Sdim/// 739327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it 740327952Sdim/// is known that the Error will always be a success value. E.g. 741327952Sdim/// 742327952Sdim/// @code{.cpp} 743327952Sdim/// // foo only attempts the fallible operation if DoFallibleOperation is 744327952Sdim/// // true. If DoFallibleOperation is false then foo always returns a Bar&. 745327952Sdim/// Expected<Bar&> foo(bool DoFallibleOperation); 746327952Sdim/// 747327952Sdim/// Bar &X = cantFail(foo(false)); 748327952Sdim/// @endcode 749327952Sdimtemplate <typename T> 750327952SdimT& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { 751327952Sdim if (ValOrErr) 752327952Sdim return *ValOrErr; 753327952Sdim else { 754327952Sdim if (!Msg) 755327952Sdim Msg = "Failure value returned from cantFail wrapped call"; 756327952Sdim llvm_unreachable(Msg); 757327952Sdim } 758327952Sdim} 759327952Sdim 760327952Sdim/// Helper for testing applicability of, and applying, handlers for 761327952Sdim/// ErrorInfo types. 762327952Sdimtemplate <typename HandlerT> 763327952Sdimclass ErrorHandlerTraits 764327952Sdim : public ErrorHandlerTraits<decltype( 765327952Sdim &std::remove_reference<HandlerT>::type::operator())> {}; 766327952Sdim 767327952Sdim// Specialization functions of the form 'Error (const ErrT&)'. 768327952Sdimtemplate <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { 769327952Sdimpublic: 770327952Sdim static bool appliesTo(const ErrorInfoBase &E) { 771327952Sdim return E.template isA<ErrT>(); 772327952Sdim } 773327952Sdim 774327952Sdim template <typename HandlerT> 775327952Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 776327952Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 777327952Sdim return H(static_cast<ErrT &>(*E)); 778327952Sdim } 779327952Sdim}; 780327952Sdim 781327952Sdim// Specialization functions of the form 'void (const ErrT&)'. 782327952Sdimtemplate <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { 783327952Sdimpublic: 784327952Sdim static bool appliesTo(const ErrorInfoBase &E) { 785327952Sdim return E.template isA<ErrT>(); 786327952Sdim } 787327952Sdim 788327952Sdim template <typename HandlerT> 789327952Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 790327952Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 791327952Sdim H(static_cast<ErrT &>(*E)); 792327952Sdim return Error::success(); 793327952Sdim } 794327952Sdim}; 795327952Sdim 796327952Sdim/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. 797327952Sdimtemplate <typename ErrT> 798327952Sdimclass ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { 799327952Sdimpublic: 800327952Sdim static bool appliesTo(const ErrorInfoBase &E) { 801327952Sdim return E.template isA<ErrT>(); 802327952Sdim } 803327952Sdim 804327952Sdim template <typename HandlerT> 805327952Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 806327952Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 807327952Sdim std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); 808327952Sdim return H(std::move(SubE)); 809327952Sdim } 810327952Sdim}; 811327952Sdim 812327952Sdim/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. 813327952Sdimtemplate <typename ErrT> 814327952Sdimclass ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { 815327952Sdimpublic: 816327952Sdim static bool appliesTo(const ErrorInfoBase &E) { 817327952Sdim return E.template isA<ErrT>(); 818327952Sdim } 819327952Sdim 820327952Sdim template <typename HandlerT> 821327952Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 822327952Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 823327952Sdim std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); 824327952Sdim H(std::move(SubE)); 825327952Sdim return Error::success(); 826327952Sdim } 827327952Sdim}; 828327952Sdim 829327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'. 830327952Sdimtemplate <typename C, typename RetT, typename ErrT> 831327952Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &)> 832327952Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 833327952Sdim 834327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'. 835327952Sdimtemplate <typename C, typename RetT, typename ErrT> 836327952Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &) const> 837327952Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 838327952Sdim 839327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'. 840327952Sdimtemplate <typename C, typename RetT, typename ErrT> 841327952Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &)> 842327952Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 843327952Sdim 844327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'. 845327952Sdimtemplate <typename C, typename RetT, typename ErrT> 846327952Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> 847327952Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 848327952Sdim 849327952Sdim/// Specialization for member functions of the form 850327952Sdim/// 'RetT (std::unique_ptr<ErrT>)'. 851327952Sdimtemplate <typename C, typename RetT, typename ErrT> 852327952Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> 853327952Sdim : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; 854327952Sdim 855327952Sdim/// Specialization for member functions of the form 856327952Sdim/// 'RetT (std::unique_ptr<ErrT>) const'. 857327952Sdimtemplate <typename C, typename RetT, typename ErrT> 858327952Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> 859327952Sdim : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; 860327952Sdim 861327952Sdiminline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { 862327952Sdim return Error(std::move(Payload)); 863327952Sdim} 864327952Sdim 865327952Sdimtemplate <typename HandlerT, typename... HandlerTs> 866327952SdimError handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, 867327952Sdim HandlerT &&Handler, HandlerTs &&... Handlers) { 868327952Sdim if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) 869327952Sdim return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), 870327952Sdim std::move(Payload)); 871327952Sdim return handleErrorImpl(std::move(Payload), 872327952Sdim std::forward<HandlerTs>(Handlers)...); 873327952Sdim} 874327952Sdim 875327952Sdim/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any 876327952Sdim/// unhandled errors (or Errors returned by handlers) are re-concatenated and 877327952Sdim/// returned. 878327952Sdim/// Because this function returns an error, its result must also be checked 879327952Sdim/// or returned. If you intend to handle all errors use handleAllErrors 880327952Sdim/// (which returns void, and will abort() on unhandled errors) instead. 881327952Sdimtemplate <typename... HandlerTs> 882327952SdimError handleErrors(Error E, HandlerTs &&... Hs) { 883327952Sdim if (!E) 884327952Sdim return Error::success(); 885327952Sdim 886327952Sdim std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); 887327952Sdim 888327952Sdim if (Payload->isA<ErrorList>()) { 889327952Sdim ErrorList &List = static_cast<ErrorList &>(*Payload); 890327952Sdim Error R; 891327952Sdim for (auto &P : List.Payloads) 892327952Sdim R = ErrorList::join( 893327952Sdim std::move(R), 894327952Sdim handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); 895327952Sdim return R; 896327952Sdim } 897327952Sdim 898327952Sdim return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); 899327952Sdim} 900327952Sdim 901341825Sdim/// Behaves the same as handleErrors, except that by contract all errors 902341825Sdim/// *must* be handled by the given handlers (i.e. there must be no remaining 903341825Sdim/// errors after running the handlers, or llvm_unreachable is called). 904327952Sdimtemplate <typename... HandlerTs> 905327952Sdimvoid handleAllErrors(Error E, HandlerTs &&... Handlers) { 906327952Sdim cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); 907327952Sdim} 908327952Sdim 909327952Sdim/// Check that E is a non-error, then drop it. 910341825Sdim/// If E is an error, llvm_unreachable will be called. 911327952Sdiminline void handleAllErrors(Error E) { 912327952Sdim cantFail(std::move(E)); 913327952Sdim} 914327952Sdim 915327952Sdim/// Handle any errors (if present) in an Expected<T>, then try a recovery path. 916327952Sdim/// 917327952Sdim/// If the incoming value is a success value it is returned unmodified. If it 918327952Sdim/// is a failure value then it the contained error is passed to handleErrors. 919327952Sdim/// If handleErrors is able to handle the error then the RecoveryPath functor 920327952Sdim/// is called to supply the final result. If handleErrors is not able to 921327952Sdim/// handle all errors then the unhandled errors are returned. 922327952Sdim/// 923327952Sdim/// This utility enables the follow pattern: 924327952Sdim/// 925327952Sdim/// @code{.cpp} 926327952Sdim/// enum FooStrategy { Aggressive, Conservative }; 927327952Sdim/// Expected<Foo> foo(FooStrategy S); 928327952Sdim/// 929327952Sdim/// auto ResultOrErr = 930327952Sdim/// handleExpected( 931327952Sdim/// foo(Aggressive), 932327952Sdim/// []() { return foo(Conservative); }, 933327952Sdim/// [](AggressiveStrategyError&) { 934327952Sdim/// // Implicitly conusme this - we'll recover by using a conservative 935327952Sdim/// // strategy. 936327952Sdim/// }); 937327952Sdim/// 938327952Sdim/// @endcode 939327952Sdimtemplate <typename T, typename RecoveryFtor, typename... HandlerTs> 940327952SdimExpected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, 941327952Sdim HandlerTs &&... Handlers) { 942327952Sdim if (ValOrErr) 943327952Sdim return ValOrErr; 944327952Sdim 945327952Sdim if (auto Err = handleErrors(ValOrErr.takeError(), 946327952Sdim std::forward<HandlerTs>(Handlers)...)) 947327952Sdim return std::move(Err); 948327952Sdim 949327952Sdim return RecoveryPath(); 950327952Sdim} 951327952Sdim 952327952Sdim/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner 953327952Sdim/// will be printed before the first one is logged. A newline will be printed 954327952Sdim/// after each error. 955327952Sdim/// 956344779Sdim/// This function is compatible with the helpers from Support/WithColor.h. You 957344779Sdim/// can pass any of them as the OS. Please consider using them instead of 958344779Sdim/// including 'error: ' in the ErrorBanner. 959344779Sdim/// 960327952Sdim/// This is useful in the base level of your program to allow clean termination 961327952Sdim/// (allowing clean deallocation of resources, etc.), while reporting error 962327952Sdim/// information to the user. 963344779Sdimvoid logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); 964327952Sdim 965327952Sdim/// Write all error messages (if any) in E to a string. The newline character 966327952Sdim/// is used to separate error messages. 967327952Sdiminline std::string toString(Error E) { 968327952Sdim SmallVector<std::string, 2> Errors; 969327952Sdim handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { 970327952Sdim Errors.push_back(EI.message()); 971327952Sdim }); 972327952Sdim return join(Errors.begin(), Errors.end(), "\n"); 973327952Sdim} 974327952Sdim 975327952Sdim/// Consume a Error without doing anything. This method should be used 976327952Sdim/// only where an error can be considered a reasonable and expected return 977327952Sdim/// value. 978327952Sdim/// 979327952Sdim/// Uses of this method are potentially indicative of design problems: If it's 980327952Sdim/// legitimate to do nothing while processing an "error", the error-producer 981327952Sdim/// might be more clearly refactored to return an Optional<T>. 982327952Sdiminline void consumeError(Error Err) { 983327952Sdim handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); 984327952Sdim} 985327952Sdim 986341825Sdim/// Helper for converting an Error to a bool. 987341825Sdim/// 988341825Sdim/// This method returns true if Err is in an error state, or false if it is 989341825Sdim/// in a success state. Puts Err in a checked state in both cases (unlike 990341825Sdim/// Error::operator bool(), which only does this for success states). 991341825Sdiminline bool errorToBool(Error Err) { 992341825Sdim bool IsError = static_cast<bool>(Err); 993341825Sdim if (IsError) 994341825Sdim consumeError(std::move(Err)); 995341825Sdim return IsError; 996341825Sdim} 997341825Sdim 998327952Sdim/// Helper for Errors used as out-parameters. 999327952Sdim/// 1000327952Sdim/// This helper is for use with the Error-as-out-parameter idiom, where an error 1001327952Sdim/// is passed to a function or method by reference, rather than being returned. 1002327952Sdim/// In such cases it is helpful to set the checked bit on entry to the function 1003327952Sdim/// so that the error can be written to (unchecked Errors abort on assignment) 1004327952Sdim/// and clear the checked bit on exit so that clients cannot accidentally forget 1005327952Sdim/// to check the result. This helper performs these actions automatically using 1006327952Sdim/// RAII: 1007327952Sdim/// 1008327952Sdim/// @code{.cpp} 1009327952Sdim/// Result foo(Error &Err) { 1010327952Sdim/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set 1011327952Sdim/// // <body of foo> 1012327952Sdim/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. 1013327952Sdim/// } 1014327952Sdim/// @endcode 1015327952Sdim/// 1016327952Sdim/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be 1017327952Sdim/// used with optional Errors (Error pointers that are allowed to be null). If 1018327952Sdim/// ErrorAsOutParameter took an Error reference, an instance would have to be 1019327952Sdim/// created inside every condition that verified that Error was non-null. By 1020327952Sdim/// taking an Error pointer we can just create one instance at the top of the 1021327952Sdim/// function. 1022327952Sdimclass ErrorAsOutParameter { 1023327952Sdimpublic: 1024327952Sdim ErrorAsOutParameter(Error *Err) : Err(Err) { 1025327952Sdim // Raise the checked bit if Err is success. 1026327952Sdim if (Err) 1027327952Sdim (void)!!*Err; 1028327952Sdim } 1029327952Sdim 1030327952Sdim ~ErrorAsOutParameter() { 1031327952Sdim // Clear the checked bit. 1032327952Sdim if (Err && !*Err) 1033327952Sdim *Err = Error::success(); 1034327952Sdim } 1035327952Sdim 1036327952Sdimprivate: 1037327952Sdim Error *Err; 1038327952Sdim}; 1039327952Sdim 1040321369Sdim/// Helper for Expected<T>s used as out-parameters. 1041321369Sdim/// 1042321369Sdim/// See ErrorAsOutParameter. 1043321369Sdimtemplate <typename T> 1044321369Sdimclass ExpectedAsOutParameter { 1045321369Sdimpublic: 1046321369Sdim ExpectedAsOutParameter(Expected<T> *ValOrErr) 1047321369Sdim : ValOrErr(ValOrErr) { 1048321369Sdim if (ValOrErr) 1049321369Sdim (void)!!*ValOrErr; 1050321369Sdim } 1051321369Sdim 1052321369Sdim ~ExpectedAsOutParameter() { 1053321369Sdim if (ValOrErr) 1054321369Sdim ValOrErr->setUnchecked(); 1055321369Sdim } 1056321369Sdim 1057321369Sdimprivate: 1058321369Sdim Expected<T> *ValOrErr; 1059321369Sdim}; 1060321369Sdim 1061303231Sdim/// This class wraps a std::error_code in a Error. 1062303231Sdim/// 1063303231Sdim/// This is useful if you're writing an interface that returns a Error 1064303231Sdim/// (or Expected) and you want to call code that still returns 1065303231Sdim/// std::error_codes. 1066303231Sdimclass ECError : public ErrorInfo<ECError> { 1067303231Sdim friend Error errorCodeToError(std::error_code); 1068314564Sdim 1069344779Sdim virtual void anchor() override; 1070344779Sdim 1071303231Sdimpublic: 1072303231Sdim void setErrorCode(std::error_code EC) { this->EC = EC; } 1073303231Sdim std::error_code convertToErrorCode() const override { return EC; } 1074303231Sdim void log(raw_ostream &OS) const override { OS << EC.message(); } 1075303231Sdim 1076303231Sdim // Used by ErrorInfo::classID. 1077303231Sdim static char ID; 1078303231Sdim 1079303231Sdimprotected: 1080303231Sdim ECError() = default; 1081303231Sdim ECError(std::error_code EC) : EC(EC) {} 1082314564Sdim 1083303231Sdim std::error_code EC; 1084303231Sdim}; 1085303231Sdim 1086303231Sdim/// The value returned by this function can be returned from convertToErrorCode 1087303231Sdim/// for Error values where no sensible translation to std::error_code exists. 1088303231Sdim/// It should only be used in this situation, and should never be used where a 1089303231Sdim/// sensible conversion to std::error_code is available, as attempts to convert 1090303231Sdim/// to/from this error will result in a fatal error. (i.e. it is a programmatic 1091303231Sdim///error to try to convert such a value). 1092303231Sdimstd::error_code inconvertibleErrorCode(); 1093303231Sdim 1094303231Sdim/// Helper for converting an std::error_code to a Error. 1095303231SdimError errorCodeToError(std::error_code EC); 1096303231Sdim 1097303231Sdim/// Helper for converting an ECError to a std::error_code. 1098303231Sdim/// 1099303231Sdim/// This method requires that Err be Error() or an ECError, otherwise it 1100303231Sdim/// will trigger a call to abort(). 1101303231Sdimstd::error_code errorToErrorCode(Error Err); 1102303231Sdim 1103303231Sdim/// Convert an ErrorOr<T> to an Expected<T>. 1104303231Sdimtemplate <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { 1105303231Sdim if (auto EC = EO.getError()) 1106303231Sdim return errorCodeToError(EC); 1107303231Sdim return std::move(*EO); 1108303231Sdim} 1109303231Sdim 1110303231Sdim/// Convert an Expected<T> to an ErrorOr<T>. 1111303231Sdimtemplate <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { 1112303231Sdim if (auto Err = E.takeError()) 1113303231Sdim return errorToErrorCode(std::move(Err)); 1114303231Sdim return std::move(*E); 1115303231Sdim} 1116303231Sdim 1117303231Sdim/// This class wraps a string in an Error. 1118303231Sdim/// 1119303231Sdim/// StringError is useful in cases where the client is not expected to be able 1120303231Sdim/// to consume the specific error message programmatically (for example, if the 1121303231Sdim/// error message is to be presented to the user). 1122344779Sdim/// 1123344779Sdim/// StringError can also be used when additional information is to be printed 1124344779Sdim/// along with a error_code message. Depending on the constructor called, this 1125344779Sdim/// class can either display: 1126344779Sdim/// 1. the error_code message (ECError behavior) 1127344779Sdim/// 2. a string 1128344779Sdim/// 3. the error_code message and a string 1129344779Sdim/// 1130344779Sdim/// These behaviors are useful when subtyping is required; for example, when a 1131344779Sdim/// specific library needs an explicit error type. In the example below, 1132344779Sdim/// PDBError is derived from StringError: 1133344779Sdim/// 1134344779Sdim/// @code{.cpp} 1135344779Sdim/// Expected<int> foo() { 1136344779Sdim/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, 1137344779Sdim/// "Additional information"); 1138344779Sdim/// } 1139344779Sdim/// @endcode 1140344779Sdim/// 1141303231Sdimclass StringError : public ErrorInfo<StringError> { 1142303231Sdimpublic: 1143303231Sdim static char ID; 1144314564Sdim 1145344779Sdim // Prints EC + S and converts to EC 1146344779Sdim StringError(std::error_code EC, const Twine &S = Twine()); 1147344779Sdim 1148344779Sdim // Prints S and converts to EC 1149303231Sdim StringError(const Twine &S, std::error_code EC); 1150314564Sdim 1151303231Sdim void log(raw_ostream &OS) const override; 1152303231Sdim std::error_code convertToErrorCode() const override; 1153314564Sdim 1154321369Sdim const std::string &getMessage() const { return Msg; } 1155321369Sdim 1156303231Sdimprivate: 1157303231Sdim std::string Msg; 1158303231Sdim std::error_code EC; 1159344779Sdim const bool PrintMsgOnly = false; 1160303231Sdim}; 1161303231Sdim 1162341825Sdim/// Create formatted StringError object. 1163341825Sdimtemplate <typename... Ts> 1164341825SdimError createStringError(std::error_code EC, char const *Fmt, 1165341825Sdim const Ts &... Vals) { 1166341825Sdim std::string Buffer; 1167341825Sdim raw_string_ostream Stream(Buffer); 1168341825Sdim Stream << format(Fmt, Vals...); 1169341825Sdim return make_error<StringError>(Stream.str(), EC); 1170341825Sdim} 1171341825Sdim 1172341825SdimError createStringError(std::error_code EC, char const *Msg); 1173341825Sdim 1174344779Sdim/// This class wraps a filename and another Error. 1175344779Sdim/// 1176344779Sdim/// In some cases, an error needs to live along a 'source' name, in order to 1177344779Sdim/// show more detailed information to the user. 1178344779Sdimclass FileError final : public ErrorInfo<FileError> { 1179344779Sdim 1180344779Sdim friend Error createFileError(std::string, Error); 1181344779Sdim 1182344779Sdimpublic: 1183344779Sdim void log(raw_ostream &OS) const override { 1184344779Sdim assert(Err && !FileName.empty() && "Trying to log after takeError()."); 1185344779Sdim OS << "'" << FileName << "': "; 1186344779Sdim Err->log(OS); 1187344779Sdim } 1188344779Sdim 1189344779Sdim Error takeError() { return Error(std::move(Err)); } 1190344779Sdim 1191344779Sdim std::error_code convertToErrorCode() const override; 1192344779Sdim 1193344779Sdim // Used by ErrorInfo::classID. 1194344779Sdim static char ID; 1195344779Sdim 1196344779Sdimprivate: 1197344779Sdim FileError(std::string F, std::unique_ptr<ErrorInfoBase> E) { 1198344779Sdim assert(E && "Cannot create FileError from Error success value."); 1199344779Sdim assert(!F.empty() && 1200344779Sdim "The file name provided to FileError must not be empty."); 1201344779Sdim FileName = F; 1202344779Sdim Err = std::move(E); 1203344779Sdim } 1204344779Sdim 1205344779Sdim static Error build(std::string F, Error E) { 1206344779Sdim return Error(std::unique_ptr<FileError>(new FileError(F, E.takePayload()))); 1207344779Sdim } 1208344779Sdim 1209344779Sdim std::string FileName; 1210344779Sdim std::unique_ptr<ErrorInfoBase> Err; 1211344779Sdim}; 1212344779Sdim 1213344779Sdim/// Concatenate a source file path and/or name with an Error. The resulting 1214344779Sdim/// Error is unchecked. 1215344779Sdiminline Error createFileError(std::string F, Error E) { 1216344779Sdim return FileError::build(F, std::move(E)); 1217344779Sdim} 1218344779Sdim 1219344779SdimError createFileError(std::string F, ErrorSuccess) = delete; 1220344779Sdim 1221303231Sdim/// Helper for check-and-exit error handling. 1222303231Sdim/// 1223303231Sdim/// For tool use only. NOT FOR USE IN LIBRARY CODE. 1224303231Sdim/// 1225303231Sdimclass ExitOnError { 1226303231Sdimpublic: 1227303231Sdim /// Create an error on exit helper. 1228303231Sdim ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) 1229303231Sdim : Banner(std::move(Banner)), 1230303231Sdim GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} 1231303231Sdim 1232303231Sdim /// Set the banner string for any errors caught by operator(). 1233303231Sdim void setBanner(std::string Banner) { this->Banner = std::move(Banner); } 1234303231Sdim 1235303231Sdim /// Set the exit-code mapper function. 1236303231Sdim void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { 1237303231Sdim this->GetExitCode = std::move(GetExitCode); 1238303231Sdim } 1239303231Sdim 1240303231Sdim /// Check Err. If it's in a failure state log the error(s) and exit. 1241303231Sdim void operator()(Error Err) const { checkError(std::move(Err)); } 1242303231Sdim 1243303231Sdim /// Check E. If it's in a success state then return the contained value. If 1244303231Sdim /// it's in a failure state log the error(s) and exit. 1245303231Sdim template <typename T> T operator()(Expected<T> &&E) const { 1246303231Sdim checkError(E.takeError()); 1247303231Sdim return std::move(*E); 1248303231Sdim } 1249303231Sdim 1250303231Sdim /// Check E. If it's in a success state then return the contained reference. If 1251303231Sdim /// it's in a failure state log the error(s) and exit. 1252303231Sdim template <typename T> T& operator()(Expected<T&> &&E) const { 1253303231Sdim checkError(E.takeError()); 1254303231Sdim return *E; 1255303231Sdim } 1256303231Sdim 1257303231Sdimprivate: 1258303231Sdim void checkError(Error Err) const { 1259303231Sdim if (Err) { 1260303231Sdim int ExitCode = GetExitCode(Err); 1261303231Sdim logAllUnhandledErrors(std::move(Err), errs(), Banner); 1262303231Sdim exit(ExitCode); 1263303231Sdim } 1264303231Sdim } 1265303231Sdim 1266303231Sdim std::string Banner; 1267303231Sdim std::function<int(const Error &)> GetExitCode; 1268303231Sdim}; 1269303231Sdim 1270344779Sdim/// Conversion from Error to LLVMErrorRef for C error bindings. 1271344779Sdiminline LLVMErrorRef wrap(Error Err) { 1272344779Sdim return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); 1273344779Sdim} 1274344779Sdim 1275344779Sdim/// Conversion from LLVMErrorRef to Error for C error bindings. 1276344779Sdiminline Error unwrap(LLVMErrorRef ErrRef) { 1277344779Sdim return Error(std::unique_ptr<ErrorInfoBase>( 1278344779Sdim reinterpret_cast<ErrorInfoBase *>(ErrRef))); 1279344779Sdim} 1280344779Sdim 1281314564Sdim} // end namespace llvm 1282303231Sdim 1283303231Sdim#endif // LLVM_SUPPORT_ERROR_H 1284