Error.h revision 321369
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 17314564Sdim#include "llvm/ADT/SmallVector.h" 18303231Sdim#include "llvm/ADT/STLExtras.h" 19303231Sdim#include "llvm/ADT/StringExtras.h" 20303231Sdim#include "llvm/ADT/Twine.h" 21314564Sdim#include "llvm/Config/abi-breaking.h" 22314564Sdim#include "llvm/Support/AlignOf.h" 23314564Sdim#include "llvm/Support/Compiler.h" 24303231Sdim#include "llvm/Support/Debug.h" 25321369Sdim#include "llvm/Support/ErrorHandling.h" 26303231Sdim#include "llvm/Support/ErrorOr.h" 27303231Sdim#include "llvm/Support/raw_ostream.h" 28314564Sdim#include <algorithm> 29314564Sdim#include <cassert> 30314564Sdim#include <cstdint> 31314564Sdim#include <cstdlib> 32314564Sdim#include <functional> 33314564Sdim#include <memory> 34314564Sdim#include <new> 35314564Sdim#include <string> 36314564Sdim#include <system_error> 37314564Sdim#include <type_traits> 38314564Sdim#include <utility> 39303231Sdim#include <vector> 40303231Sdim 41303231Sdimnamespace llvm { 42303231Sdim 43314564Sdimclass ErrorSuccess; 44303231Sdim 45303231Sdim/// Base class for error info classes. Do not extend this directly: Extend 46303231Sdim/// the ErrorInfo template subclass instead. 47303231Sdimclass ErrorInfoBase { 48303231Sdimpublic: 49314564Sdim virtual ~ErrorInfoBase() = default; 50303231Sdim 51303231Sdim /// Print an error message to an output stream. 52303231Sdim virtual void log(raw_ostream &OS) const = 0; 53303231Sdim 54303231Sdim /// Return the error message as a string. 55303231Sdim virtual std::string message() const { 56303231Sdim std::string Msg; 57303231Sdim raw_string_ostream OS(Msg); 58303231Sdim log(OS); 59303231Sdim return OS.str(); 60303231Sdim } 61303231Sdim 62303231Sdim /// Convert this error to a std::error_code. 63303231Sdim /// 64303231Sdim /// This is a temporary crutch to enable interaction with code still 65303231Sdim /// using std::error_code. It will be removed in the future. 66303231Sdim virtual std::error_code convertToErrorCode() const = 0; 67303231Sdim 68321369Sdim // Returns the class ID for this type. 69321369Sdim static const void *classID() { return &ID; } 70321369Sdim 71321369Sdim // Returns the class ID for the dynamic type of this ErrorInfoBase instance. 72321369Sdim virtual const void *dynamicClassID() const = 0; 73321369Sdim 74303231Sdim // Check whether this instance is a subclass of the class identified by 75303231Sdim // ClassID. 76303231Sdim virtual bool isA(const void *const ClassID) const { 77303231Sdim return ClassID == classID(); 78303231Sdim } 79303231Sdim 80303231Sdim // Check whether this instance is a subclass of ErrorInfoT. 81303231Sdim template <typename ErrorInfoT> bool isA() const { 82303231Sdim return isA(ErrorInfoT::classID()); 83303231Sdim } 84303231Sdim 85303231Sdimprivate: 86303231Sdim virtual void anchor(); 87314564Sdim 88303231Sdim static char ID; 89303231Sdim}; 90303231Sdim 91303231Sdim/// Lightweight error class with error context and mandatory checking. 92303231Sdim/// 93303231Sdim/// Instances of this class wrap a ErrorInfoBase pointer. Failure states 94303231Sdim/// are represented by setting the pointer to a ErrorInfoBase subclass 95303231Sdim/// instance containing information describing the failure. Success is 96303231Sdim/// represented by a null pointer value. 97303231Sdim/// 98303231Sdim/// Instances of Error also contains a 'Checked' flag, which must be set 99303231Sdim/// before the destructor is called, otherwise the destructor will trigger a 100303231Sdim/// runtime error. This enforces at runtime the requirement that all Error 101303231Sdim/// instances be checked or returned to the caller. 102303231Sdim/// 103303231Sdim/// There are two ways to set the checked flag, depending on what state the 104303231Sdim/// Error instance is in. For Error instances indicating success, it 105303231Sdim/// is sufficient to invoke the boolean conversion operator. E.g.: 106303231Sdim/// 107314564Sdim/// @code{.cpp} 108303231Sdim/// Error foo(<...>); 109303231Sdim/// 110303231Sdim/// if (auto E = foo(<...>)) 111303231Sdim/// return E; // <- Return E if it is in the error state. 112303231Sdim/// // We have verified that E was in the success state. It can now be safely 113303231Sdim/// // destroyed. 114314564Sdim/// @endcode 115303231Sdim/// 116303231Sdim/// A success value *can not* be dropped. For example, just calling 'foo(<...>)' 117303231Sdim/// without testing the return value will raise a runtime error, even if foo 118303231Sdim/// returns success. 119303231Sdim/// 120303231Sdim/// For Error instances representing failure, you must use either the 121303231Sdim/// handleErrors or handleAllErrors function with a typed handler. E.g.: 122303231Sdim/// 123314564Sdim/// @code{.cpp} 124303231Sdim/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { 125303231Sdim/// // Custom error info. 126303231Sdim/// }; 127303231Sdim/// 128303231Sdim/// Error foo(<...>) { return make_error<MyErrorInfo>(...); } 129303231Sdim/// 130303231Sdim/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. 131303231Sdim/// auto NewE = 132303231Sdim/// handleErrors(E, 133303231Sdim/// [](const MyErrorInfo &M) { 134303231Sdim/// // Deal with the error. 135303231Sdim/// }, 136303231Sdim/// [](std::unique_ptr<OtherError> M) -> Error { 137303231Sdim/// if (canHandle(*M)) { 138303231Sdim/// // handle error. 139303231Sdim/// return Error::success(); 140303231Sdim/// } 141303231Sdim/// // Couldn't handle this error instance. Pass it up the stack. 142303231Sdim/// return Error(std::move(M)); 143303231Sdim/// ); 144303231Sdim/// // Note - we must check or return NewE in case any of the handlers 145303231Sdim/// // returned a new error. 146314564Sdim/// @endcode 147303231Sdim/// 148303231Sdim/// The handleAllErrors function is identical to handleErrors, except 149303231Sdim/// that it has a void return type, and requires all errors to be handled and 150303231Sdim/// no new errors be returned. It prevents errors (assuming they can all be 151303231Sdim/// handled) from having to be bubbled all the way to the top-level. 152303231Sdim/// 153303231Sdim/// *All* Error instances must be checked before destruction, even if 154303231Sdim/// they're moved-assigned or constructed from Success values that have already 155303231Sdim/// been checked. This enforces checking through all levels of the call stack. 156314564Sdimclass LLVM_NODISCARD Error { 157303231Sdim // ErrorList needs to be able to yank ErrorInfoBase pointers out of this 158303231Sdim // class to add to the error list. 159303231Sdim friend class ErrorList; 160303231Sdim 161303231Sdim // handleErrors needs to be able to set the Checked flag. 162303231Sdim template <typename... HandlerTs> 163303231Sdim friend Error handleErrors(Error E, HandlerTs &&... Handlers); 164303231Sdim 165303231Sdim // Expected<T> needs to be able to steal the payload when constructed from an 166303231Sdim // error. 167314564Sdim template <typename T> friend class Expected; 168303231Sdim 169314564Sdimprotected: 170303231Sdim /// Create a success value. Prefer using 'Error::success()' for readability 171321369Sdim Error() { 172303231Sdim setPtr(nullptr); 173303231Sdim setChecked(false); 174303231Sdim } 175303231Sdim 176314564Sdimpublic: 177314564Sdim /// Create a success value. 178314564Sdim static ErrorSuccess success(); 179303231Sdim 180303231Sdim // Errors are not copy-constructable. 181303231Sdim Error(const Error &Other) = delete; 182303231Sdim 183303231Sdim /// Move-construct an error value. The newly constructed error is considered 184303231Sdim /// unchecked, even if the source error had been checked. The original error 185303231Sdim /// becomes a checked Success value, regardless of its original state. 186321369Sdim Error(Error &&Other) { 187303231Sdim setChecked(true); 188303231Sdim *this = std::move(Other); 189303231Sdim } 190303231Sdim 191303231Sdim /// Create an error value. Prefer using the 'make_error' function, but 192303231Sdim /// this constructor can be useful when "re-throwing" errors from handlers. 193303231Sdim Error(std::unique_ptr<ErrorInfoBase> Payload) { 194303231Sdim setPtr(Payload.release()); 195303231Sdim setChecked(false); 196303231Sdim } 197303231Sdim 198303231Sdim // Errors are not copy-assignable. 199303231Sdim Error &operator=(const Error &Other) = delete; 200303231Sdim 201303231Sdim /// Move-assign an error value. The current error must represent success, you 202303231Sdim /// you cannot overwrite an unhandled error. The current error is then 203303231Sdim /// considered unchecked. The source error becomes a checked success value, 204303231Sdim /// regardless of its original state. 205303231Sdim Error &operator=(Error &&Other) { 206303231Sdim // Don't allow overwriting of unchecked values. 207303231Sdim assertIsChecked(); 208303231Sdim setPtr(Other.getPtr()); 209303231Sdim 210303231Sdim // This Error is unchecked, even if the source error was checked. 211303231Sdim setChecked(false); 212303231Sdim 213303231Sdim // Null out Other's payload and set its checked bit. 214303231Sdim Other.setPtr(nullptr); 215303231Sdim Other.setChecked(true); 216303231Sdim 217303231Sdim return *this; 218303231Sdim } 219303231Sdim 220303231Sdim /// Destroy a Error. Fails with a call to abort() if the error is 221303231Sdim /// unchecked. 222303231Sdim ~Error() { 223303231Sdim assertIsChecked(); 224303231Sdim delete getPtr(); 225303231Sdim } 226303231Sdim 227303231Sdim /// Bool conversion. Returns true if this Error is in a failure state, 228303231Sdim /// and false if it is in an accept state. If the error is in a Success state 229303231Sdim /// it will be considered checked. 230303231Sdim explicit operator bool() { 231303231Sdim setChecked(getPtr() == nullptr); 232303231Sdim return getPtr() != nullptr; 233303231Sdim } 234303231Sdim 235303231Sdim /// Check whether one error is a subclass of another. 236303231Sdim template <typename ErrT> bool isA() const { 237303231Sdim return getPtr() && getPtr()->isA(ErrT::classID()); 238303231Sdim } 239303231Sdim 240321369Sdim /// Returns the dynamic class id of this error, or null if this is a success 241321369Sdim /// value. 242321369Sdim const void* dynamicClassID() const { 243321369Sdim if (!getPtr()) 244321369Sdim return nullptr; 245321369Sdim return getPtr()->dynamicClassID(); 246321369Sdim } 247321369Sdim 248303231Sdimprivate: 249303231Sdim void assertIsChecked() { 250314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 251303231Sdim if (!getChecked() || getPtr()) { 252303231Sdim dbgs() << "Program aborted due to an unhandled Error:\n"; 253303231Sdim if (getPtr()) 254303231Sdim getPtr()->log(dbgs()); 255303231Sdim else 256303231Sdim dbgs() 257303231Sdim << "Error value was Success. (Note: Success values must still be " 258303231Sdim "checked prior to being destroyed).\n"; 259303231Sdim abort(); 260303231Sdim } 261303231Sdim#endif 262303231Sdim } 263303231Sdim 264303231Sdim ErrorInfoBase *getPtr() const { 265314564Sdim return reinterpret_cast<ErrorInfoBase*>( 266314564Sdim reinterpret_cast<uintptr_t>(Payload) & 267314564Sdim ~static_cast<uintptr_t>(0x1)); 268303231Sdim } 269303231Sdim 270303231Sdim void setPtr(ErrorInfoBase *EI) { 271314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 272314564Sdim Payload = reinterpret_cast<ErrorInfoBase*>( 273314564Sdim (reinterpret_cast<uintptr_t>(EI) & 274314564Sdim ~static_cast<uintptr_t>(0x1)) | 275314564Sdim (reinterpret_cast<uintptr_t>(Payload) & 0x1)); 276303231Sdim#else 277303231Sdim Payload = EI; 278303231Sdim#endif 279303231Sdim } 280303231Sdim 281303231Sdim bool getChecked() const { 282314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 283314564Sdim return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; 284303231Sdim#else 285303231Sdim return true; 286303231Sdim#endif 287303231Sdim } 288303231Sdim 289303231Sdim void setChecked(bool V) { 290314564Sdim Payload = reinterpret_cast<ErrorInfoBase*>( 291314564Sdim (reinterpret_cast<uintptr_t>(Payload) & 292314564Sdim ~static_cast<uintptr_t>(0x1)) | 293314564Sdim (V ? 0 : 1)); 294303231Sdim } 295303231Sdim 296303231Sdim std::unique_ptr<ErrorInfoBase> takePayload() { 297303231Sdim std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); 298303231Sdim setPtr(nullptr); 299303231Sdim setChecked(true); 300303231Sdim return Tmp; 301303231Sdim } 302303231Sdim 303321369Sdim ErrorInfoBase *Payload = nullptr; 304303231Sdim}; 305303231Sdim 306314564Sdim/// Subclass of Error for the sole purpose of identifying the success path in 307314564Sdim/// the type system. This allows to catch invalid conversion to Expected<T> at 308314564Sdim/// compile time. 309314564Sdimclass ErrorSuccess : public Error {}; 310314564Sdim 311314564Sdiminline ErrorSuccess Error::success() { return ErrorSuccess(); } 312314564Sdim 313303231Sdim/// Make a Error instance representing failure using the given error info 314303231Sdim/// type. 315303231Sdimtemplate <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { 316303231Sdim return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); 317303231Sdim} 318303231Sdim 319303231Sdim/// Base class for user error types. Users should declare their error types 320303231Sdim/// like: 321303231Sdim/// 322303231Sdim/// class MyError : public ErrorInfo<MyError> { 323303231Sdim/// .... 324303231Sdim/// }; 325303231Sdim/// 326303231Sdim/// This class provides an implementation of the ErrorInfoBase::kind 327303231Sdim/// method, which is used by the Error RTTI system. 328303231Sdimtemplate <typename ThisErrT, typename ParentErrT = ErrorInfoBase> 329303231Sdimclass ErrorInfo : public ParentErrT { 330303231Sdimpublic: 331321369Sdim static const void *classID() { return &ThisErrT::ID; } 332321369Sdim 333321369Sdim const void *dynamicClassID() const override { return &ThisErrT::ID; } 334321369Sdim 335303231Sdim bool isA(const void *const ClassID) const override { 336303231Sdim return ClassID == classID() || ParentErrT::isA(ClassID); 337303231Sdim } 338303231Sdim}; 339303231Sdim 340303231Sdim/// Special ErrorInfo subclass representing a list of ErrorInfos. 341303231Sdim/// Instances of this class are constructed by joinError. 342303231Sdimclass ErrorList final : public ErrorInfo<ErrorList> { 343303231Sdim // handleErrors needs to be able to iterate the payload list of an 344303231Sdim // ErrorList. 345303231Sdim template <typename... HandlerTs> 346303231Sdim friend Error handleErrors(Error E, HandlerTs &&... Handlers); 347303231Sdim 348303231Sdim // joinErrors is implemented in terms of join. 349303231Sdim friend Error joinErrors(Error, Error); 350303231Sdim 351303231Sdimpublic: 352303231Sdim void log(raw_ostream &OS) const override { 353303231Sdim OS << "Multiple errors:\n"; 354303231Sdim for (auto &ErrPayload : Payloads) { 355303231Sdim ErrPayload->log(OS); 356303231Sdim OS << "\n"; 357303231Sdim } 358303231Sdim } 359303231Sdim 360303231Sdim std::error_code convertToErrorCode() const override; 361303231Sdim 362303231Sdim // Used by ErrorInfo::classID. 363303231Sdim static char ID; 364303231Sdim 365303231Sdimprivate: 366303231Sdim ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, 367303231Sdim std::unique_ptr<ErrorInfoBase> Payload2) { 368303231Sdim assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && 369303231Sdim "ErrorList constructor payloads should be singleton errors"); 370303231Sdim Payloads.push_back(std::move(Payload1)); 371303231Sdim Payloads.push_back(std::move(Payload2)); 372303231Sdim } 373303231Sdim 374303231Sdim static Error join(Error E1, Error E2) { 375303231Sdim if (!E1) 376303231Sdim return E2; 377303231Sdim if (!E2) 378303231Sdim return E1; 379303231Sdim if (E1.isA<ErrorList>()) { 380303231Sdim auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); 381303231Sdim if (E2.isA<ErrorList>()) { 382303231Sdim auto E2Payload = E2.takePayload(); 383303231Sdim auto &E2List = static_cast<ErrorList &>(*E2Payload); 384303231Sdim for (auto &Payload : E2List.Payloads) 385303231Sdim E1List.Payloads.push_back(std::move(Payload)); 386303231Sdim } else 387303231Sdim E1List.Payloads.push_back(E2.takePayload()); 388303231Sdim 389303231Sdim return E1; 390303231Sdim } 391303231Sdim if (E2.isA<ErrorList>()) { 392303231Sdim auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); 393303231Sdim E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); 394303231Sdim return E2; 395303231Sdim } 396303231Sdim return Error(std::unique_ptr<ErrorList>( 397303231Sdim new ErrorList(E1.takePayload(), E2.takePayload()))); 398303231Sdim } 399303231Sdim 400303231Sdim std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; 401303231Sdim}; 402303231Sdim 403303231Sdim/// Concatenate errors. The resulting Error is unchecked, and contains the 404303231Sdim/// ErrorInfo(s), if any, contained in E1, followed by the 405303231Sdim/// ErrorInfo(s), if any, contained in E2. 406303231Sdiminline Error joinErrors(Error E1, Error E2) { 407303231Sdim return ErrorList::join(std::move(E1), std::move(E2)); 408303231Sdim} 409303231Sdim 410303231Sdim/// Helper for testing applicability of, and applying, handlers for 411303231Sdim/// ErrorInfo types. 412303231Sdimtemplate <typename HandlerT> 413303231Sdimclass ErrorHandlerTraits 414303231Sdim : public ErrorHandlerTraits<decltype( 415303231Sdim &std::remove_reference<HandlerT>::type::operator())> {}; 416303231Sdim 417303231Sdim// Specialization functions of the form 'Error (const ErrT&)'. 418303231Sdimtemplate <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { 419303231Sdimpublic: 420303231Sdim static bool appliesTo(const ErrorInfoBase &E) { 421303231Sdim return E.template isA<ErrT>(); 422303231Sdim } 423303231Sdim 424303231Sdim template <typename HandlerT> 425303231Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 426303231Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 427303231Sdim return H(static_cast<ErrT &>(*E)); 428303231Sdim } 429303231Sdim}; 430303231Sdim 431303231Sdim// Specialization functions of the form 'void (const ErrT&)'. 432303231Sdimtemplate <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { 433303231Sdimpublic: 434303231Sdim static bool appliesTo(const ErrorInfoBase &E) { 435303231Sdim return E.template isA<ErrT>(); 436303231Sdim } 437303231Sdim 438303231Sdim template <typename HandlerT> 439303231Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 440303231Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 441303231Sdim H(static_cast<ErrT &>(*E)); 442303231Sdim return Error::success(); 443303231Sdim } 444303231Sdim}; 445303231Sdim 446303231Sdim/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. 447303231Sdimtemplate <typename ErrT> 448303231Sdimclass ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { 449303231Sdimpublic: 450303231Sdim static bool appliesTo(const ErrorInfoBase &E) { 451303231Sdim return E.template isA<ErrT>(); 452303231Sdim } 453303231Sdim 454303231Sdim template <typename HandlerT> 455303231Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 456303231Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 457303231Sdim std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); 458303231Sdim return H(std::move(SubE)); 459303231Sdim } 460303231Sdim}; 461303231Sdim 462303231Sdim/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. 463303231Sdimtemplate <typename ErrT> 464303231Sdimclass ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { 465303231Sdimpublic: 466303231Sdim static bool appliesTo(const ErrorInfoBase &E) { 467303231Sdim return E.template isA<ErrT>(); 468303231Sdim } 469303231Sdim 470303231Sdim template <typename HandlerT> 471303231Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 472303231Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 473303231Sdim std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); 474303231Sdim H(std::move(SubE)); 475303231Sdim return Error::success(); 476303231Sdim } 477303231Sdim}; 478303231Sdim 479303231Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'. 480303231Sdimtemplate <typename C, typename RetT, typename ErrT> 481303231Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &)> 482303231Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 483303231Sdim 484303231Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'. 485303231Sdimtemplate <typename C, typename RetT, typename ErrT> 486303231Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &) const> 487303231Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 488303231Sdim 489303231Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'. 490303231Sdimtemplate <typename C, typename RetT, typename ErrT> 491303231Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &)> 492303231Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 493303231Sdim 494303231Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'. 495303231Sdimtemplate <typename C, typename RetT, typename ErrT> 496303231Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> 497303231Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 498303231Sdim 499303231Sdim/// Specialization for member functions of the form 500303231Sdim/// 'RetT (std::unique_ptr<ErrT>) const'. 501303231Sdimtemplate <typename C, typename RetT, typename ErrT> 502303231Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> 503303231Sdim : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; 504303231Sdim 505303231Sdim/// Specialization for member functions of the form 506303231Sdim/// 'RetT (std::unique_ptr<ErrT>) const'. 507303231Sdimtemplate <typename C, typename RetT, typename ErrT> 508303231Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> 509303231Sdim : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; 510303231Sdim 511303231Sdiminline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { 512303231Sdim return Error(std::move(Payload)); 513303231Sdim} 514303231Sdim 515303231Sdimtemplate <typename HandlerT, typename... HandlerTs> 516303231SdimError handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, 517303231Sdim HandlerT &&Handler, HandlerTs &&... Handlers) { 518303231Sdim if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) 519303231Sdim return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), 520303231Sdim std::move(Payload)); 521303231Sdim return handleErrorImpl(std::move(Payload), 522303231Sdim std::forward<HandlerTs>(Handlers)...); 523303231Sdim} 524303231Sdim 525303231Sdim/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any 526303231Sdim/// unhandled errors (or Errors returned by handlers) are re-concatenated and 527303231Sdim/// returned. 528303231Sdim/// Because this function returns an error, its result must also be checked 529303231Sdim/// or returned. If you intend to handle all errors use handleAllErrors 530303231Sdim/// (which returns void, and will abort() on unhandled errors) instead. 531303231Sdimtemplate <typename... HandlerTs> 532303231SdimError handleErrors(Error E, HandlerTs &&... Hs) { 533303231Sdim if (!E) 534303231Sdim return Error::success(); 535303231Sdim 536303231Sdim std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); 537303231Sdim 538303231Sdim if (Payload->isA<ErrorList>()) { 539303231Sdim ErrorList &List = static_cast<ErrorList &>(*Payload); 540303231Sdim Error R; 541303231Sdim for (auto &P : List.Payloads) 542303231Sdim R = ErrorList::join( 543303231Sdim std::move(R), 544303231Sdim handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); 545303231Sdim return R; 546303231Sdim } 547303231Sdim 548303231Sdim return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); 549303231Sdim} 550303231Sdim 551303231Sdim/// Behaves the same as handleErrors, except that it requires that all 552303231Sdim/// errors be handled by the given handlers. If any unhandled error remains 553303231Sdim/// after the handlers have run, abort() will be called. 554303231Sdimtemplate <typename... HandlerTs> 555303231Sdimvoid handleAllErrors(Error E, HandlerTs &&... Handlers) { 556303231Sdim auto F = handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...); 557303231Sdim // Cast 'F' to bool to set the 'Checked' flag if it's a success value: 558303231Sdim (void)!F; 559303231Sdim} 560303231Sdim 561303231Sdim/// Check that E is a non-error, then drop it. 562303231Sdiminline void handleAllErrors(Error E) { 563303231Sdim // Cast 'E' to a bool to set the 'Checked' flag if it's a success value: 564303231Sdim (void)!E; 565303231Sdim} 566303231Sdim 567303231Sdim/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner 568303231Sdim/// will be printed before the first one is logged. A newline will be printed 569303231Sdim/// after each error. 570303231Sdim/// 571303231Sdim/// This is useful in the base level of your program to allow clean termination 572303231Sdim/// (allowing clean deallocation of resources, etc.), while reporting error 573303231Sdim/// information to the user. 574303231Sdimvoid logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner); 575303231Sdim 576303231Sdim/// Write all error messages (if any) in E to a string. The newline character 577303231Sdim/// is used to separate error messages. 578303231Sdiminline std::string toString(Error E) { 579303231Sdim SmallVector<std::string, 2> Errors; 580303231Sdim handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { 581303231Sdim Errors.push_back(EI.message()); 582303231Sdim }); 583303231Sdim return join(Errors.begin(), Errors.end(), "\n"); 584303231Sdim} 585303231Sdim 586303231Sdim/// Consume a Error without doing anything. This method should be used 587303231Sdim/// only where an error can be considered a reasonable and expected return 588303231Sdim/// value. 589303231Sdim/// 590303231Sdim/// Uses of this method are potentially indicative of design problems: If it's 591303231Sdim/// legitimate to do nothing while processing an "error", the error-producer 592303231Sdim/// might be more clearly refactored to return an Optional<T>. 593303231Sdiminline void consumeError(Error Err) { 594303231Sdim handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); 595303231Sdim} 596303231Sdim 597303231Sdim/// Helper for Errors used as out-parameters. 598303231Sdim/// 599303231Sdim/// This helper is for use with the Error-as-out-parameter idiom, where an error 600303231Sdim/// is passed to a function or method by reference, rather than being returned. 601303231Sdim/// In such cases it is helpful to set the checked bit on entry to the function 602303231Sdim/// so that the error can be written to (unchecked Errors abort on assignment) 603303231Sdim/// and clear the checked bit on exit so that clients cannot accidentally forget 604303231Sdim/// to check the result. This helper performs these actions automatically using 605303231Sdim/// RAII: 606303231Sdim/// 607314564Sdim/// @code{.cpp} 608314564Sdim/// Result foo(Error &Err) { 609314564Sdim/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set 610314564Sdim/// // <body of foo> 611314564Sdim/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. 612314564Sdim/// } 613314564Sdim/// @endcode 614314564Sdim/// 615314564Sdim/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be 616314564Sdim/// used with optional Errors (Error pointers that are allowed to be null). If 617314564Sdim/// ErrorAsOutParameter took an Error reference, an instance would have to be 618314564Sdim/// created inside every condition that verified that Error was non-null. By 619314564Sdim/// taking an Error pointer we can just create one instance at the top of the 620314564Sdim/// function. 621303231Sdimclass ErrorAsOutParameter { 622303231Sdimpublic: 623314564Sdim ErrorAsOutParameter(Error *Err) : Err(Err) { 624303231Sdim // Raise the checked bit if Err is success. 625314564Sdim if (Err) 626314564Sdim (void)!!*Err; 627303231Sdim } 628314564Sdim 629303231Sdim ~ErrorAsOutParameter() { 630303231Sdim // Clear the checked bit. 631314564Sdim if (Err && !*Err) 632314564Sdim *Err = Error::success(); 633303231Sdim } 634303231Sdim 635303231Sdimprivate: 636314564Sdim Error *Err; 637303231Sdim}; 638303231Sdim 639303231Sdim/// Tagged union holding either a T or a Error. 640303231Sdim/// 641303231Sdim/// This class parallels ErrorOr, but replaces error_code with Error. Since 642303231Sdim/// Error cannot be copied, this class replaces getError() with 643303231Sdim/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the 644303231Sdim/// error class type. 645314564Sdimtemplate <class T> class LLVM_NODISCARD Expected { 646321369Sdim template <class T1> friend class ExpectedAsOutParameter; 647303231Sdim template <class OtherT> friend class Expected; 648321369Sdim 649303231Sdim static const bool isRef = std::is_reference<T>::value; 650303231Sdim 651321369Sdim using wrap = ReferenceStorage<typename std::remove_reference<T>::type>; 652303231Sdim 653321369Sdim using error_type = std::unique_ptr<ErrorInfoBase>; 654321369Sdim 655303231Sdimpublic: 656321369Sdim using storage_type = typename std::conditional<isRef, wrap, T>::type; 657321369Sdim using value_type = T; 658303231Sdim 659303231Sdimprivate: 660321369Sdim using reference = typename std::remove_reference<T>::type &; 661321369Sdim using const_reference = const typename std::remove_reference<T>::type &; 662321369Sdim using pointer = typename std::remove_reference<T>::type *; 663321369Sdim using const_pointer = const typename std::remove_reference<T>::type *; 664303231Sdim 665303231Sdimpublic: 666303231Sdim /// Create an Expected<T> error value from the given Error. 667303231Sdim Expected(Error Err) 668303231Sdim : HasError(true) 669314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 670314564Sdim // Expected is unchecked upon construction in Debug builds. 671314564Sdim , Unchecked(true) 672303231Sdim#endif 673303231Sdim { 674303231Sdim assert(Err && "Cannot create Expected<T> from Error success value."); 675314564Sdim new (getErrorStorage()) error_type(Err.takePayload()); 676303231Sdim } 677303231Sdim 678314564Sdim /// Forbid to convert from Error::success() implicitly, this avoids having 679314564Sdim /// Expected<T> foo() { return Error::success(); } which compiles otherwise 680314564Sdim /// but triggers the assertion above. 681314564Sdim Expected(ErrorSuccess) = delete; 682314564Sdim 683303231Sdim /// Create an Expected<T> success value from the given OtherT value, which 684303231Sdim /// must be convertible to T. 685303231Sdim template <typename OtherT> 686303231Sdim Expected(OtherT &&Val, 687303231Sdim typename std::enable_if<std::is_convertible<OtherT, T>::value>::type 688303231Sdim * = nullptr) 689303231Sdim : HasError(false) 690314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 691314564Sdim // Expected is unchecked upon construction in Debug builds. 692314564Sdim , Unchecked(true) 693303231Sdim#endif 694303231Sdim { 695303231Sdim new (getStorage()) storage_type(std::forward<OtherT>(Val)); 696303231Sdim } 697303231Sdim 698303231Sdim /// Move construct an Expected<T> value. 699303231Sdim Expected(Expected &&Other) { moveConstruct(std::move(Other)); } 700303231Sdim 701303231Sdim /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT 702303231Sdim /// must be convertible to T. 703303231Sdim template <class OtherT> 704303231Sdim Expected(Expected<OtherT> &&Other, 705303231Sdim typename std::enable_if<std::is_convertible<OtherT, T>::value>::type 706303231Sdim * = nullptr) { 707303231Sdim moveConstruct(std::move(Other)); 708303231Sdim } 709303231Sdim 710303231Sdim /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT 711303231Sdim /// isn't convertible to T. 712303231Sdim template <class OtherT> 713303231Sdim explicit Expected( 714303231Sdim Expected<OtherT> &&Other, 715303231Sdim typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * = 716303231Sdim nullptr) { 717303231Sdim moveConstruct(std::move(Other)); 718303231Sdim } 719303231Sdim 720303231Sdim /// Move-assign from another Expected<T>. 721303231Sdim Expected &operator=(Expected &&Other) { 722303231Sdim moveAssign(std::move(Other)); 723303231Sdim return *this; 724303231Sdim } 725303231Sdim 726303231Sdim /// Destroy an Expected<T>. 727303231Sdim ~Expected() { 728303231Sdim assertIsChecked(); 729303231Sdim if (!HasError) 730303231Sdim getStorage()->~storage_type(); 731303231Sdim else 732303231Sdim getErrorStorage()->~error_type(); 733303231Sdim } 734303231Sdim 735303231Sdim /// \brief Return false if there is an error. 736303231Sdim explicit operator bool() { 737314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 738314564Sdim Unchecked = HasError; 739303231Sdim#endif 740303231Sdim return !HasError; 741303231Sdim } 742303231Sdim 743303231Sdim /// \brief Returns a reference to the stored T value. 744303231Sdim reference get() { 745303231Sdim assertIsChecked(); 746303231Sdim return *getStorage(); 747303231Sdim } 748303231Sdim 749303231Sdim /// \brief Returns a const reference to the stored T value. 750303231Sdim const_reference get() const { 751303231Sdim assertIsChecked(); 752303231Sdim return const_cast<Expected<T> *>(this)->get(); 753303231Sdim } 754303231Sdim 755303231Sdim /// \brief Check that this Expected<T> is an error of type ErrT. 756303231Sdim template <typename ErrT> bool errorIsA() const { 757321369Sdim return HasError && (*getErrorStorage())->template isA<ErrT>(); 758303231Sdim } 759303231Sdim 760303231Sdim /// \brief Take ownership of the stored error. 761303231Sdim /// After calling this the Expected<T> is in an indeterminate state that can 762303231Sdim /// only be safely destructed. No further calls (beside the destructor) should 763303231Sdim /// be made on the Expected<T> vaule. 764303231Sdim Error takeError() { 765314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 766314564Sdim Unchecked = false; 767303231Sdim#endif 768303231Sdim return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); 769303231Sdim } 770303231Sdim 771303231Sdim /// \brief Returns a pointer to the stored T value. 772303231Sdim pointer operator->() { 773303231Sdim assertIsChecked(); 774303231Sdim return toPointer(getStorage()); 775303231Sdim } 776303231Sdim 777303231Sdim /// \brief Returns a const pointer to the stored T value. 778303231Sdim const_pointer operator->() const { 779303231Sdim assertIsChecked(); 780303231Sdim return toPointer(getStorage()); 781303231Sdim } 782303231Sdim 783303231Sdim /// \brief Returns a reference to the stored T value. 784303231Sdim reference operator*() { 785303231Sdim assertIsChecked(); 786303231Sdim return *getStorage(); 787303231Sdim } 788303231Sdim 789303231Sdim /// \brief Returns a const reference to the stored T value. 790303231Sdim const_reference operator*() const { 791303231Sdim assertIsChecked(); 792303231Sdim return *getStorage(); 793303231Sdim } 794303231Sdim 795303231Sdimprivate: 796303231Sdim template <class T1> 797303231Sdim static bool compareThisIfSameType(const T1 &a, const T1 &b) { 798303231Sdim return &a == &b; 799303231Sdim } 800303231Sdim 801303231Sdim template <class T1, class T2> 802303231Sdim static bool compareThisIfSameType(const T1 &a, const T2 &b) { 803303231Sdim return false; 804303231Sdim } 805303231Sdim 806303231Sdim template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { 807303231Sdim HasError = Other.HasError; 808314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 809314564Sdim Unchecked = true; 810314564Sdim Other.Unchecked = false; 811303231Sdim#endif 812303231Sdim 813303231Sdim if (!HasError) 814303231Sdim new (getStorage()) storage_type(std::move(*Other.getStorage())); 815303231Sdim else 816303231Sdim new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); 817303231Sdim } 818303231Sdim 819303231Sdim template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { 820303231Sdim assertIsChecked(); 821303231Sdim 822303231Sdim if (compareThisIfSameType(*this, Other)) 823303231Sdim return; 824303231Sdim 825303231Sdim this->~Expected(); 826303231Sdim new (this) Expected(std::move(Other)); 827303231Sdim } 828303231Sdim 829303231Sdim pointer toPointer(pointer Val) { return Val; } 830303231Sdim 831303231Sdim const_pointer toPointer(const_pointer Val) const { return Val; } 832303231Sdim 833303231Sdim pointer toPointer(wrap *Val) { return &Val->get(); } 834303231Sdim 835303231Sdim const_pointer toPointer(const wrap *Val) const { return &Val->get(); } 836303231Sdim 837303231Sdim storage_type *getStorage() { 838303231Sdim assert(!HasError && "Cannot get value when an error exists!"); 839303231Sdim return reinterpret_cast<storage_type *>(TStorage.buffer); 840303231Sdim } 841303231Sdim 842303231Sdim const storage_type *getStorage() const { 843303231Sdim assert(!HasError && "Cannot get value when an error exists!"); 844303231Sdim return reinterpret_cast<const storage_type *>(TStorage.buffer); 845303231Sdim } 846303231Sdim 847303231Sdim error_type *getErrorStorage() { 848303231Sdim assert(HasError && "Cannot get error when a value exists!"); 849303231Sdim return reinterpret_cast<error_type *>(ErrorStorage.buffer); 850303231Sdim } 851303231Sdim 852321369Sdim const error_type *getErrorStorage() const { 853321369Sdim assert(HasError && "Cannot get error when a value exists!"); 854321369Sdim return reinterpret_cast<const error_type *>(ErrorStorage.buffer); 855321369Sdim } 856321369Sdim 857321369Sdim // Used by ExpectedAsOutParameter to reset the checked flag. 858321369Sdim void setUnchecked() { 859321369Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 860321369Sdim Unchecked = true; 861321369Sdim#endif 862321369Sdim } 863321369Sdim 864303231Sdim void assertIsChecked() { 865314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 866314564Sdim if (Unchecked) { 867303231Sdim dbgs() << "Expected<T> must be checked before access or destruction.\n"; 868303231Sdim if (HasError) { 869303231Sdim dbgs() << "Unchecked Expected<T> contained error:\n"; 870303231Sdim (*getErrorStorage())->log(dbgs()); 871303231Sdim } else 872303231Sdim dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " 873303231Sdim "values in success mode must still be checked prior to being " 874303231Sdim "destroyed).\n"; 875303231Sdim abort(); 876303231Sdim } 877303231Sdim#endif 878303231Sdim } 879303231Sdim 880303231Sdim union { 881303231Sdim AlignedCharArrayUnion<storage_type> TStorage; 882303231Sdim AlignedCharArrayUnion<error_type> ErrorStorage; 883303231Sdim }; 884303231Sdim bool HasError : 1; 885314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 886314564Sdim bool Unchecked : 1; 887303231Sdim#endif 888303231Sdim}; 889303231Sdim 890321369Sdim/// Helper for Expected<T>s used as out-parameters. 891321369Sdim/// 892321369Sdim/// See ErrorAsOutParameter. 893321369Sdimtemplate <typename T> 894321369Sdimclass ExpectedAsOutParameter { 895321369Sdimpublic: 896321369Sdim ExpectedAsOutParameter(Expected<T> *ValOrErr) 897321369Sdim : ValOrErr(ValOrErr) { 898321369Sdim if (ValOrErr) 899321369Sdim (void)!!*ValOrErr; 900321369Sdim } 901321369Sdim 902321369Sdim ~ExpectedAsOutParameter() { 903321369Sdim if (ValOrErr) 904321369Sdim ValOrErr->setUnchecked(); 905321369Sdim } 906321369Sdim 907321369Sdimprivate: 908321369Sdim Expected<T> *ValOrErr; 909321369Sdim}; 910321369Sdim 911303231Sdim/// This class wraps a std::error_code in a Error. 912303231Sdim/// 913303231Sdim/// This is useful if you're writing an interface that returns a Error 914303231Sdim/// (or Expected) and you want to call code that still returns 915303231Sdim/// std::error_codes. 916303231Sdimclass ECError : public ErrorInfo<ECError> { 917303231Sdim friend Error errorCodeToError(std::error_code); 918314564Sdim 919303231Sdimpublic: 920303231Sdim void setErrorCode(std::error_code EC) { this->EC = EC; } 921303231Sdim std::error_code convertToErrorCode() const override { return EC; } 922303231Sdim void log(raw_ostream &OS) const override { OS << EC.message(); } 923303231Sdim 924303231Sdim // Used by ErrorInfo::classID. 925303231Sdim static char ID; 926303231Sdim 927303231Sdimprotected: 928303231Sdim ECError() = default; 929303231Sdim ECError(std::error_code EC) : EC(EC) {} 930314564Sdim 931303231Sdim std::error_code EC; 932303231Sdim}; 933303231Sdim 934303231Sdim/// The value returned by this function can be returned from convertToErrorCode 935303231Sdim/// for Error values where no sensible translation to std::error_code exists. 936303231Sdim/// It should only be used in this situation, and should never be used where a 937303231Sdim/// sensible conversion to std::error_code is available, as attempts to convert 938303231Sdim/// to/from this error will result in a fatal error. (i.e. it is a programmatic 939303231Sdim///error to try to convert such a value). 940303231Sdimstd::error_code inconvertibleErrorCode(); 941303231Sdim 942303231Sdim/// Helper for converting an std::error_code to a Error. 943303231SdimError errorCodeToError(std::error_code EC); 944303231Sdim 945303231Sdim/// Helper for converting an ECError to a std::error_code. 946303231Sdim/// 947303231Sdim/// This method requires that Err be Error() or an ECError, otherwise it 948303231Sdim/// will trigger a call to abort(). 949303231Sdimstd::error_code errorToErrorCode(Error Err); 950303231Sdim 951303231Sdim/// Convert an ErrorOr<T> to an Expected<T>. 952303231Sdimtemplate <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { 953303231Sdim if (auto EC = EO.getError()) 954303231Sdim return errorCodeToError(EC); 955303231Sdim return std::move(*EO); 956303231Sdim} 957303231Sdim 958303231Sdim/// Convert an Expected<T> to an ErrorOr<T>. 959303231Sdimtemplate <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { 960303231Sdim if (auto Err = E.takeError()) 961303231Sdim return errorToErrorCode(std::move(Err)); 962303231Sdim return std::move(*E); 963303231Sdim} 964303231Sdim 965303231Sdim/// This class wraps a string in an Error. 966303231Sdim/// 967303231Sdim/// StringError is useful in cases where the client is not expected to be able 968303231Sdim/// to consume the specific error message programmatically (for example, if the 969303231Sdim/// error message is to be presented to the user). 970303231Sdimclass StringError : public ErrorInfo<StringError> { 971303231Sdimpublic: 972303231Sdim static char ID; 973314564Sdim 974303231Sdim StringError(const Twine &S, std::error_code EC); 975314564Sdim 976303231Sdim void log(raw_ostream &OS) const override; 977303231Sdim std::error_code convertToErrorCode() const override; 978314564Sdim 979321369Sdim const std::string &getMessage() const { return Msg; } 980321369Sdim 981303231Sdimprivate: 982303231Sdim std::string Msg; 983303231Sdim std::error_code EC; 984303231Sdim}; 985303231Sdim 986303231Sdim/// Helper for check-and-exit error handling. 987303231Sdim/// 988303231Sdim/// For tool use only. NOT FOR USE IN LIBRARY CODE. 989303231Sdim/// 990303231Sdimclass ExitOnError { 991303231Sdimpublic: 992303231Sdim /// Create an error on exit helper. 993303231Sdim ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) 994303231Sdim : Banner(std::move(Banner)), 995303231Sdim GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} 996303231Sdim 997303231Sdim /// Set the banner string for any errors caught by operator(). 998303231Sdim void setBanner(std::string Banner) { this->Banner = std::move(Banner); } 999303231Sdim 1000303231Sdim /// Set the exit-code mapper function. 1001303231Sdim void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { 1002303231Sdim this->GetExitCode = std::move(GetExitCode); 1003303231Sdim } 1004303231Sdim 1005303231Sdim /// Check Err. If it's in a failure state log the error(s) and exit. 1006303231Sdim void operator()(Error Err) const { checkError(std::move(Err)); } 1007303231Sdim 1008303231Sdim /// Check E. If it's in a success state then return the contained value. If 1009303231Sdim /// it's in a failure state log the error(s) and exit. 1010303231Sdim template <typename T> T operator()(Expected<T> &&E) const { 1011303231Sdim checkError(E.takeError()); 1012303231Sdim return std::move(*E); 1013303231Sdim } 1014303231Sdim 1015303231Sdim /// Check E. If it's in a success state then return the contained reference. If 1016303231Sdim /// it's in a failure state log the error(s) and exit. 1017303231Sdim template <typename T> T& operator()(Expected<T&> &&E) const { 1018303231Sdim checkError(E.takeError()); 1019303231Sdim return *E; 1020303231Sdim } 1021303231Sdim 1022303231Sdimprivate: 1023303231Sdim void checkError(Error Err) const { 1024303231Sdim if (Err) { 1025303231Sdim int ExitCode = GetExitCode(Err); 1026303231Sdim logAllUnhandledErrors(std::move(Err), errs(), Banner); 1027303231Sdim exit(ExitCode); 1028303231Sdim } 1029303231Sdim } 1030303231Sdim 1031303231Sdim std::string Banner; 1032303231Sdim std::function<int(const Error &)> GetExitCode; 1033303231Sdim}; 1034303231Sdim 1035303231Sdim/// Report a serious error, calling any installed error handler. See 1036303231Sdim/// ErrorHandling.h. 1037303231SdimLLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, 1038303231Sdim bool gen_crash_diag = true); 1039303231Sdim 1040321369Sdim/// Report a fatal error if Err is a failure value. 1041321369Sdim/// 1042321369Sdim/// This function can be used to wrap calls to fallible functions ONLY when it 1043321369Sdim/// is known that the Error will always be a success value. E.g. 1044321369Sdim/// 1045321369Sdim/// @code{.cpp} 1046321369Sdim/// // foo only attempts the fallible operation if DoFallibleOperation is 1047321369Sdim/// // true. If DoFallibleOperation is false then foo always returns 1048321369Sdim/// // Error::success(). 1049321369Sdim/// Error foo(bool DoFallibleOperation); 1050321369Sdim/// 1051321369Sdim/// cantFail(foo(false)); 1052321369Sdim/// @endcode 1053321369Sdiminline void cantFail(Error Err) { 1054321369Sdim if (Err) 1055321369Sdim llvm_unreachable("Failure value returned from cantFail wrapped call"); 1056321369Sdim} 1057321369Sdim 1058321369Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and 1059321369Sdim/// returns the contained value. 1060321369Sdim/// 1061321369Sdim/// This function can be used to wrap calls to fallible functions ONLY when it 1062321369Sdim/// is known that the Error will always be a success value. E.g. 1063321369Sdim/// 1064321369Sdim/// @code{.cpp} 1065321369Sdim/// // foo only attempts the fallible operation if DoFallibleOperation is 1066321369Sdim/// // true. If DoFallibleOperation is false then foo always returns an int. 1067321369Sdim/// Expected<int> foo(bool DoFallibleOperation); 1068321369Sdim/// 1069321369Sdim/// int X = cantFail(foo(false)); 1070321369Sdim/// @endcode 1071321369Sdimtemplate <typename T> 1072321369SdimT cantFail(Expected<T> ValOrErr) { 1073321369Sdim if (ValOrErr) 1074321369Sdim return std::move(*ValOrErr); 1075321369Sdim else 1076321369Sdim llvm_unreachable("Failure value returned from cantFail wrapped call"); 1077321369Sdim} 1078321369Sdim 1079321369Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and 1080321369Sdim/// returns the contained reference. 1081321369Sdim/// 1082321369Sdim/// This function can be used to wrap calls to fallible functions ONLY when it 1083321369Sdim/// is known that the Error will always be a success value. E.g. 1084321369Sdim/// 1085321369Sdim/// @code{.cpp} 1086321369Sdim/// // foo only attempts the fallible operation if DoFallibleOperation is 1087321369Sdim/// // true. If DoFallibleOperation is false then foo always returns a Bar&. 1088321369Sdim/// Expected<Bar&> foo(bool DoFallibleOperation); 1089321369Sdim/// 1090321369Sdim/// Bar &X = cantFail(foo(false)); 1091321369Sdim/// @endcode 1092321369Sdimtemplate <typename T> 1093321369SdimT& cantFail(Expected<T&> ValOrErr) { 1094321369Sdim if (ValOrErr) 1095321369Sdim return *ValOrErr; 1096321369Sdim else 1097321369Sdim llvm_unreachable("Failure value returned from cantFail wrapped call"); 1098321369Sdim} 1099321369Sdim 1100314564Sdim} // end namespace llvm 1101303231Sdim 1102303231Sdim#endif // LLVM_SUPPORT_ERROR_H 1103