Error.h revision 353358
1321369Sdim//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// 2303231Sdim// 3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4353358Sdim// See https://llvm.org/LICENSE.txt for license information. 5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6303231Sdim// 7303231Sdim//===----------------------------------------------------------------------===// 8303231Sdim// 9303231Sdim// This file defines an API used to report recoverable errors. 10303231Sdim// 11303231Sdim//===----------------------------------------------------------------------===// 12303231Sdim 13303231Sdim#ifndef LLVM_SUPPORT_ERROR_H 14303231Sdim#define LLVM_SUPPORT_ERROR_H 15303231Sdim 16344779Sdim#include "llvm-c/Error.h" 17344779Sdim#include "llvm/ADT/STLExtras.h" 18314564Sdim#include "llvm/ADT/SmallVector.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" 27341825Sdim#include "llvm/Support/Format.h" 28303231Sdim#include "llvm/Support/raw_ostream.h" 29314564Sdim#include <algorithm> 30314564Sdim#include <cassert> 31314564Sdim#include <cstdint> 32314564Sdim#include <cstdlib> 33314564Sdim#include <functional> 34314564Sdim#include <memory> 35314564Sdim#include <new> 36314564Sdim#include <string> 37314564Sdim#include <system_error> 38314564Sdim#include <type_traits> 39314564Sdim#include <utility> 40303231Sdim#include <vector> 41303231Sdim 42303231Sdimnamespace llvm { 43303231Sdim 44314564Sdimclass ErrorSuccess; 45303231Sdim 46303231Sdim/// Base class for error info classes. Do not extend this directly: Extend 47303231Sdim/// the ErrorInfo template subclass instead. 48303231Sdimclass ErrorInfoBase { 49303231Sdimpublic: 50314564Sdim virtual ~ErrorInfoBase() = default; 51303231Sdim 52303231Sdim /// Print an error message to an output stream. 53303231Sdim virtual void log(raw_ostream &OS) const = 0; 54303231Sdim 55303231Sdim /// Return the error message as a string. 56303231Sdim virtual std::string message() const { 57303231Sdim std::string Msg; 58303231Sdim raw_string_ostream OS(Msg); 59303231Sdim log(OS); 60303231Sdim return OS.str(); 61303231Sdim } 62303231Sdim 63303231Sdim /// Convert this error to a std::error_code. 64303231Sdim /// 65303231Sdim /// This is a temporary crutch to enable interaction with code still 66303231Sdim /// using std::error_code. It will be removed in the future. 67303231Sdim virtual std::error_code convertToErrorCode() const = 0; 68303231Sdim 69321369Sdim // Returns the class ID for this type. 70321369Sdim static const void *classID() { return &ID; } 71321369Sdim 72321369Sdim // Returns the class ID for the dynamic type of this ErrorInfoBase instance. 73321369Sdim virtual const void *dynamicClassID() const = 0; 74321369Sdim 75303231Sdim // Check whether this instance is a subclass of the class identified by 76303231Sdim // ClassID. 77303231Sdim virtual bool isA(const void *const ClassID) const { 78303231Sdim return ClassID == classID(); 79303231Sdim } 80303231Sdim 81303231Sdim // Check whether this instance is a subclass of ErrorInfoT. 82303231Sdim template <typename ErrorInfoT> bool isA() const { 83303231Sdim return isA(ErrorInfoT::classID()); 84303231Sdim } 85303231Sdim 86303231Sdimprivate: 87303231Sdim virtual void anchor(); 88314564Sdim 89303231Sdim static char ID; 90303231Sdim}; 91303231Sdim 92303231Sdim/// Lightweight error class with error context and mandatory checking. 93303231Sdim/// 94303231Sdim/// Instances of this class wrap a ErrorInfoBase pointer. Failure states 95303231Sdim/// are represented by setting the pointer to a ErrorInfoBase subclass 96303231Sdim/// instance containing information describing the failure. Success is 97303231Sdim/// represented by a null pointer value. 98303231Sdim/// 99303231Sdim/// Instances of Error also contains a 'Checked' flag, which must be set 100303231Sdim/// before the destructor is called, otherwise the destructor will trigger a 101303231Sdim/// runtime error. This enforces at runtime the requirement that all Error 102303231Sdim/// instances be checked or returned to the caller. 103303231Sdim/// 104303231Sdim/// There are two ways to set the checked flag, depending on what state the 105303231Sdim/// Error instance is in. For Error instances indicating success, it 106303231Sdim/// is sufficient to invoke the boolean conversion operator. E.g.: 107303231Sdim/// 108314564Sdim/// @code{.cpp} 109303231Sdim/// Error foo(<...>); 110303231Sdim/// 111303231Sdim/// if (auto E = foo(<...>)) 112303231Sdim/// return E; // <- Return E if it is in the error state. 113303231Sdim/// // We have verified that E was in the success state. It can now be safely 114303231Sdim/// // destroyed. 115314564Sdim/// @endcode 116303231Sdim/// 117303231Sdim/// A success value *can not* be dropped. For example, just calling 'foo(<...>)' 118303231Sdim/// without testing the return value will raise a runtime error, even if foo 119303231Sdim/// returns success. 120303231Sdim/// 121303231Sdim/// For Error instances representing failure, you must use either the 122303231Sdim/// handleErrors or handleAllErrors function with a typed handler. E.g.: 123303231Sdim/// 124314564Sdim/// @code{.cpp} 125303231Sdim/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { 126303231Sdim/// // Custom error info. 127303231Sdim/// }; 128303231Sdim/// 129303231Sdim/// Error foo(<...>) { return make_error<MyErrorInfo>(...); } 130303231Sdim/// 131303231Sdim/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. 132303231Sdim/// auto NewE = 133303231Sdim/// handleErrors(E, 134303231Sdim/// [](const MyErrorInfo &M) { 135303231Sdim/// // Deal with the error. 136303231Sdim/// }, 137303231Sdim/// [](std::unique_ptr<OtherError> M) -> Error { 138303231Sdim/// if (canHandle(*M)) { 139303231Sdim/// // handle error. 140303231Sdim/// return Error::success(); 141303231Sdim/// } 142303231Sdim/// // Couldn't handle this error instance. Pass it up the stack. 143303231Sdim/// return Error(std::move(M)); 144303231Sdim/// ); 145303231Sdim/// // Note - we must check or return NewE in case any of the handlers 146303231Sdim/// // returned a new error. 147314564Sdim/// @endcode 148303231Sdim/// 149303231Sdim/// The handleAllErrors function is identical to handleErrors, except 150303231Sdim/// that it has a void return type, and requires all errors to be handled and 151303231Sdim/// no new errors be returned. It prevents errors (assuming they can all be 152303231Sdim/// handled) from having to be bubbled all the way to the top-level. 153303231Sdim/// 154303231Sdim/// *All* Error instances must be checked before destruction, even if 155303231Sdim/// they're moved-assigned or constructed from Success values that have already 156303231Sdim/// been checked. This enforces checking through all levels of the call stack. 157314564Sdimclass LLVM_NODISCARD Error { 158344779Sdim // Both ErrorList and FileError need to be able to yank ErrorInfoBase 159344779Sdim // pointers out of this class to add to the error list. 160303231Sdim friend class ErrorList; 161344779Sdim friend class FileError; 162303231Sdim 163303231Sdim // handleErrors needs to be able to set the Checked flag. 164303231Sdim template <typename... HandlerTs> 165303231Sdim friend Error handleErrors(Error E, HandlerTs &&... Handlers); 166303231Sdim 167303231Sdim // Expected<T> needs to be able to steal the payload when constructed from an 168303231Sdim // error. 169314564Sdim template <typename T> friend class Expected; 170303231Sdim 171344779Sdim // wrap needs to be able to steal the payload. 172344779Sdim friend LLVMErrorRef wrap(Error); 173344779Sdim 174314564Sdimprotected: 175303231Sdim /// Create a success value. Prefer using 'Error::success()' for readability 176321369Sdim Error() { 177303231Sdim setPtr(nullptr); 178303231Sdim setChecked(false); 179303231Sdim } 180303231Sdim 181314564Sdimpublic: 182314564Sdim /// Create a success value. 183314564Sdim static ErrorSuccess success(); 184303231Sdim 185303231Sdim // Errors are not copy-constructable. 186303231Sdim Error(const Error &Other) = delete; 187303231Sdim 188303231Sdim /// Move-construct an error value. The newly constructed error is considered 189303231Sdim /// unchecked, even if the source error had been checked. The original error 190303231Sdim /// becomes a checked Success value, regardless of its original state. 191321369Sdim Error(Error &&Other) { 192303231Sdim setChecked(true); 193303231Sdim *this = std::move(Other); 194303231Sdim } 195303231Sdim 196303231Sdim /// Create an error value. Prefer using the 'make_error' function, but 197303231Sdim /// this constructor can be useful when "re-throwing" errors from handlers. 198303231Sdim Error(std::unique_ptr<ErrorInfoBase> Payload) { 199303231Sdim setPtr(Payload.release()); 200303231Sdim setChecked(false); 201303231Sdim } 202303231Sdim 203303231Sdim // Errors are not copy-assignable. 204303231Sdim Error &operator=(const Error &Other) = delete; 205303231Sdim 206303231Sdim /// Move-assign an error value. The current error must represent success, you 207303231Sdim /// you cannot overwrite an unhandled error. The current error is then 208303231Sdim /// considered unchecked. The source error becomes a checked success value, 209303231Sdim /// regardless of its original state. 210303231Sdim Error &operator=(Error &&Other) { 211303231Sdim // Don't allow overwriting of unchecked values. 212303231Sdim assertIsChecked(); 213303231Sdim setPtr(Other.getPtr()); 214303231Sdim 215303231Sdim // This Error is unchecked, even if the source error was checked. 216303231Sdim setChecked(false); 217303231Sdim 218303231Sdim // Null out Other's payload and set its checked bit. 219303231Sdim Other.setPtr(nullptr); 220303231Sdim Other.setChecked(true); 221303231Sdim 222303231Sdim return *this; 223303231Sdim } 224303231Sdim 225303231Sdim /// Destroy a Error. Fails with a call to abort() if the error is 226303231Sdim /// unchecked. 227303231Sdim ~Error() { 228303231Sdim assertIsChecked(); 229303231Sdim delete getPtr(); 230303231Sdim } 231303231Sdim 232303231Sdim /// Bool conversion. Returns true if this Error is in a failure state, 233303231Sdim /// and false if it is in an accept state. If the error is in a Success state 234303231Sdim /// it will be considered checked. 235303231Sdim explicit operator bool() { 236303231Sdim setChecked(getPtr() == nullptr); 237303231Sdim return getPtr() != nullptr; 238303231Sdim } 239303231Sdim 240303231Sdim /// Check whether one error is a subclass of another. 241303231Sdim template <typename ErrT> bool isA() const { 242303231Sdim return getPtr() && getPtr()->isA(ErrT::classID()); 243303231Sdim } 244303231Sdim 245321369Sdim /// Returns the dynamic class id of this error, or null if this is a success 246321369Sdim /// value. 247321369Sdim const void* dynamicClassID() const { 248321369Sdim if (!getPtr()) 249321369Sdim return nullptr; 250321369Sdim return getPtr()->dynamicClassID(); 251321369Sdim } 252321369Sdim 253303231Sdimprivate: 254327952Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 255327952Sdim // assertIsChecked() happens very frequently, but under normal circumstances 256327952Sdim // is supposed to be a no-op. So we want it to be inlined, but having a bunch 257327952Sdim // of debug prints can cause the function to be too large for inlining. So 258327952Sdim // it's important that we define this function out of line so that it can't be 259327952Sdim // inlined. 260327952Sdim LLVM_ATTRIBUTE_NORETURN 261327952Sdim void fatalUncheckedError() const; 262327952Sdim#endif 263327952Sdim 264303231Sdim void assertIsChecked() { 265314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 266327952Sdim if (LLVM_UNLIKELY(!getChecked() || getPtr())) 267327952Sdim fatalUncheckedError(); 268303231Sdim#endif 269303231Sdim } 270303231Sdim 271303231Sdim ErrorInfoBase *getPtr() const { 272314564Sdim return reinterpret_cast<ErrorInfoBase*>( 273314564Sdim reinterpret_cast<uintptr_t>(Payload) & 274314564Sdim ~static_cast<uintptr_t>(0x1)); 275303231Sdim } 276303231Sdim 277303231Sdim void setPtr(ErrorInfoBase *EI) { 278314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 279314564Sdim Payload = reinterpret_cast<ErrorInfoBase*>( 280314564Sdim (reinterpret_cast<uintptr_t>(EI) & 281314564Sdim ~static_cast<uintptr_t>(0x1)) | 282314564Sdim (reinterpret_cast<uintptr_t>(Payload) & 0x1)); 283303231Sdim#else 284303231Sdim Payload = EI; 285303231Sdim#endif 286303231Sdim } 287303231Sdim 288303231Sdim bool getChecked() const { 289314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 290314564Sdim return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; 291303231Sdim#else 292303231Sdim return true; 293303231Sdim#endif 294303231Sdim } 295303231Sdim 296303231Sdim void setChecked(bool V) { 297314564Sdim Payload = reinterpret_cast<ErrorInfoBase*>( 298314564Sdim (reinterpret_cast<uintptr_t>(Payload) & 299314564Sdim ~static_cast<uintptr_t>(0x1)) | 300314564Sdim (V ? 0 : 1)); 301303231Sdim } 302303231Sdim 303303231Sdim std::unique_ptr<ErrorInfoBase> takePayload() { 304303231Sdim std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); 305303231Sdim setPtr(nullptr); 306303231Sdim setChecked(true); 307303231Sdim return Tmp; 308303231Sdim } 309303231Sdim 310341825Sdim friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { 311341825Sdim if (auto P = E.getPtr()) 312341825Sdim P->log(OS); 313341825Sdim else 314341825Sdim OS << "success"; 315341825Sdim return OS; 316341825Sdim } 317341825Sdim 318321369Sdim ErrorInfoBase *Payload = nullptr; 319303231Sdim}; 320303231Sdim 321314564Sdim/// Subclass of Error for the sole purpose of identifying the success path in 322314564Sdim/// the type system. This allows to catch invalid conversion to Expected<T> at 323314564Sdim/// compile time. 324344779Sdimclass ErrorSuccess final : public Error {}; 325314564Sdim 326314564Sdiminline ErrorSuccess Error::success() { return ErrorSuccess(); } 327314564Sdim 328303231Sdim/// Make a Error instance representing failure using the given error info 329303231Sdim/// type. 330303231Sdimtemplate <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { 331303231Sdim return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); 332303231Sdim} 333303231Sdim 334303231Sdim/// Base class for user error types. Users should declare their error types 335303231Sdim/// like: 336303231Sdim/// 337303231Sdim/// class MyError : public ErrorInfo<MyError> { 338303231Sdim/// .... 339303231Sdim/// }; 340303231Sdim/// 341303231Sdim/// This class provides an implementation of the ErrorInfoBase::kind 342303231Sdim/// method, which is used by the Error RTTI system. 343303231Sdimtemplate <typename ThisErrT, typename ParentErrT = ErrorInfoBase> 344303231Sdimclass ErrorInfo : public ParentErrT { 345303231Sdimpublic: 346344779Sdim using ParentErrT::ParentErrT; // inherit constructors 347344779Sdim 348321369Sdim static const void *classID() { return &ThisErrT::ID; } 349321369Sdim 350321369Sdim const void *dynamicClassID() const override { return &ThisErrT::ID; } 351321369Sdim 352303231Sdim bool isA(const void *const ClassID) const override { 353303231Sdim return ClassID == classID() || ParentErrT::isA(ClassID); 354303231Sdim } 355303231Sdim}; 356303231Sdim 357303231Sdim/// Special ErrorInfo subclass representing a list of ErrorInfos. 358303231Sdim/// Instances of this class are constructed by joinError. 359303231Sdimclass ErrorList final : public ErrorInfo<ErrorList> { 360303231Sdim // handleErrors needs to be able to iterate the payload list of an 361303231Sdim // ErrorList. 362303231Sdim template <typename... HandlerTs> 363303231Sdim friend Error handleErrors(Error E, HandlerTs &&... Handlers); 364303231Sdim 365303231Sdim // joinErrors is implemented in terms of join. 366303231Sdim friend Error joinErrors(Error, Error); 367303231Sdim 368303231Sdimpublic: 369303231Sdim void log(raw_ostream &OS) const override { 370303231Sdim OS << "Multiple errors:\n"; 371303231Sdim for (auto &ErrPayload : Payloads) { 372303231Sdim ErrPayload->log(OS); 373303231Sdim OS << "\n"; 374303231Sdim } 375303231Sdim } 376303231Sdim 377303231Sdim std::error_code convertToErrorCode() const override; 378303231Sdim 379303231Sdim // Used by ErrorInfo::classID. 380303231Sdim static char ID; 381303231Sdim 382303231Sdimprivate: 383303231Sdim ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, 384303231Sdim std::unique_ptr<ErrorInfoBase> Payload2) { 385303231Sdim assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && 386303231Sdim "ErrorList constructor payloads should be singleton errors"); 387303231Sdim Payloads.push_back(std::move(Payload1)); 388303231Sdim Payloads.push_back(std::move(Payload2)); 389303231Sdim } 390303231Sdim 391303231Sdim static Error join(Error E1, Error E2) { 392303231Sdim if (!E1) 393303231Sdim return E2; 394303231Sdim if (!E2) 395303231Sdim return E1; 396303231Sdim if (E1.isA<ErrorList>()) { 397303231Sdim auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); 398303231Sdim if (E2.isA<ErrorList>()) { 399303231Sdim auto E2Payload = E2.takePayload(); 400303231Sdim auto &E2List = static_cast<ErrorList &>(*E2Payload); 401303231Sdim for (auto &Payload : E2List.Payloads) 402303231Sdim E1List.Payloads.push_back(std::move(Payload)); 403303231Sdim } else 404303231Sdim E1List.Payloads.push_back(E2.takePayload()); 405303231Sdim 406303231Sdim return E1; 407303231Sdim } 408303231Sdim if (E2.isA<ErrorList>()) { 409303231Sdim auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); 410303231Sdim E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); 411303231Sdim return E2; 412303231Sdim } 413303231Sdim return Error(std::unique_ptr<ErrorList>( 414303231Sdim new ErrorList(E1.takePayload(), E2.takePayload()))); 415303231Sdim } 416303231Sdim 417303231Sdim std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; 418303231Sdim}; 419303231Sdim 420303231Sdim/// Concatenate errors. The resulting Error is unchecked, and contains the 421303231Sdim/// ErrorInfo(s), if any, contained in E1, followed by the 422303231Sdim/// ErrorInfo(s), if any, contained in E2. 423303231Sdiminline Error joinErrors(Error E1, Error E2) { 424303231Sdim return ErrorList::join(std::move(E1), std::move(E2)); 425303231Sdim} 426303231Sdim 427303231Sdim/// Tagged union holding either a T or a Error. 428303231Sdim/// 429303231Sdim/// This class parallels ErrorOr, but replaces error_code with Error. Since 430303231Sdim/// Error cannot be copied, this class replaces getError() with 431303231Sdim/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the 432303231Sdim/// error class type. 433314564Sdimtemplate <class T> class LLVM_NODISCARD Expected { 434321369Sdim template <class T1> friend class ExpectedAsOutParameter; 435303231Sdim template <class OtherT> friend class Expected; 436321369Sdim 437303231Sdim static const bool isRef = std::is_reference<T>::value; 438303231Sdim 439341825Sdim using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>; 440303231Sdim 441321369Sdim using error_type = std::unique_ptr<ErrorInfoBase>; 442321369Sdim 443303231Sdimpublic: 444321369Sdim using storage_type = typename std::conditional<isRef, wrap, T>::type; 445321369Sdim using value_type = T; 446303231Sdim 447303231Sdimprivate: 448321369Sdim using reference = typename std::remove_reference<T>::type &; 449321369Sdim using const_reference = const typename std::remove_reference<T>::type &; 450321369Sdim using pointer = typename std::remove_reference<T>::type *; 451321369Sdim using const_pointer = const typename std::remove_reference<T>::type *; 452303231Sdim 453303231Sdimpublic: 454303231Sdim /// Create an Expected<T> error value from the given Error. 455303231Sdim Expected(Error Err) 456303231Sdim : HasError(true) 457314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 458314564Sdim // Expected is unchecked upon construction in Debug builds. 459314564Sdim , Unchecked(true) 460303231Sdim#endif 461303231Sdim { 462303231Sdim assert(Err && "Cannot create Expected<T> from Error success value."); 463314564Sdim new (getErrorStorage()) error_type(Err.takePayload()); 464303231Sdim } 465303231Sdim 466314564Sdim /// Forbid to convert from Error::success() implicitly, this avoids having 467314564Sdim /// Expected<T> foo() { return Error::success(); } which compiles otherwise 468314564Sdim /// but triggers the assertion above. 469314564Sdim Expected(ErrorSuccess) = delete; 470314564Sdim 471303231Sdim /// Create an Expected<T> success value from the given OtherT value, which 472303231Sdim /// must be convertible to T. 473303231Sdim template <typename OtherT> 474303231Sdim Expected(OtherT &&Val, 475303231Sdim typename std::enable_if<std::is_convertible<OtherT, T>::value>::type 476303231Sdim * = nullptr) 477303231Sdim : HasError(false) 478314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 479314564Sdim // Expected is unchecked upon construction in Debug builds. 480314564Sdim , Unchecked(true) 481303231Sdim#endif 482303231Sdim { 483303231Sdim new (getStorage()) storage_type(std::forward<OtherT>(Val)); 484303231Sdim } 485303231Sdim 486303231Sdim /// Move construct an Expected<T> value. 487303231Sdim Expected(Expected &&Other) { moveConstruct(std::move(Other)); } 488303231Sdim 489303231Sdim /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT 490303231Sdim /// must be convertible to T. 491303231Sdim template <class OtherT> 492303231Sdim Expected(Expected<OtherT> &&Other, 493303231Sdim typename std::enable_if<std::is_convertible<OtherT, T>::value>::type 494303231Sdim * = nullptr) { 495303231Sdim moveConstruct(std::move(Other)); 496303231Sdim } 497303231Sdim 498303231Sdim /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT 499303231Sdim /// isn't convertible to T. 500303231Sdim template <class OtherT> 501303231Sdim explicit Expected( 502303231Sdim Expected<OtherT> &&Other, 503303231Sdim typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * = 504303231Sdim nullptr) { 505303231Sdim moveConstruct(std::move(Other)); 506303231Sdim } 507303231Sdim 508303231Sdim /// Move-assign from another Expected<T>. 509303231Sdim Expected &operator=(Expected &&Other) { 510303231Sdim moveAssign(std::move(Other)); 511303231Sdim return *this; 512303231Sdim } 513303231Sdim 514303231Sdim /// Destroy an Expected<T>. 515303231Sdim ~Expected() { 516303231Sdim assertIsChecked(); 517303231Sdim if (!HasError) 518303231Sdim getStorage()->~storage_type(); 519303231Sdim else 520303231Sdim getErrorStorage()->~error_type(); 521303231Sdim } 522303231Sdim 523341825Sdim /// Return false if there is an error. 524303231Sdim explicit operator bool() { 525314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 526314564Sdim Unchecked = HasError; 527303231Sdim#endif 528303231Sdim return !HasError; 529303231Sdim } 530303231Sdim 531341825Sdim /// Returns a reference to the stored T value. 532303231Sdim reference get() { 533303231Sdim assertIsChecked(); 534303231Sdim return *getStorage(); 535303231Sdim } 536303231Sdim 537341825Sdim /// Returns a const reference to the stored T value. 538303231Sdim const_reference get() const { 539303231Sdim assertIsChecked(); 540303231Sdim return const_cast<Expected<T> *>(this)->get(); 541303231Sdim } 542303231Sdim 543341825Sdim /// Check that this Expected<T> is an error of type ErrT. 544303231Sdim template <typename ErrT> bool errorIsA() const { 545321369Sdim return HasError && (*getErrorStorage())->template isA<ErrT>(); 546303231Sdim } 547303231Sdim 548341825Sdim /// Take ownership of the stored error. 549303231Sdim /// After calling this the Expected<T> is in an indeterminate state that can 550303231Sdim /// only be safely destructed. No further calls (beside the destructor) should 551303231Sdim /// be made on the Expected<T> vaule. 552303231Sdim Error takeError() { 553314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 554314564Sdim Unchecked = false; 555303231Sdim#endif 556303231Sdim return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); 557303231Sdim } 558303231Sdim 559341825Sdim /// Returns a pointer to the stored T value. 560303231Sdim pointer operator->() { 561303231Sdim assertIsChecked(); 562303231Sdim return toPointer(getStorage()); 563303231Sdim } 564303231Sdim 565341825Sdim /// Returns a const pointer to the stored T value. 566303231Sdim const_pointer operator->() const { 567303231Sdim assertIsChecked(); 568303231Sdim return toPointer(getStorage()); 569303231Sdim } 570303231Sdim 571341825Sdim /// Returns a reference to the stored T value. 572303231Sdim reference operator*() { 573303231Sdim assertIsChecked(); 574303231Sdim return *getStorage(); 575303231Sdim } 576303231Sdim 577341825Sdim /// Returns a const reference to the stored T value. 578303231Sdim const_reference operator*() const { 579303231Sdim assertIsChecked(); 580303231Sdim return *getStorage(); 581303231Sdim } 582303231Sdim 583303231Sdimprivate: 584303231Sdim template <class T1> 585303231Sdim static bool compareThisIfSameType(const T1 &a, const T1 &b) { 586303231Sdim return &a == &b; 587303231Sdim } 588303231Sdim 589303231Sdim template <class T1, class T2> 590303231Sdim static bool compareThisIfSameType(const T1 &a, const T2 &b) { 591303231Sdim return false; 592303231Sdim } 593303231Sdim 594303231Sdim template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { 595303231Sdim HasError = Other.HasError; 596314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 597314564Sdim Unchecked = true; 598314564Sdim Other.Unchecked = false; 599303231Sdim#endif 600303231Sdim 601303231Sdim if (!HasError) 602303231Sdim new (getStorage()) storage_type(std::move(*Other.getStorage())); 603303231Sdim else 604303231Sdim new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); 605303231Sdim } 606303231Sdim 607303231Sdim template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { 608303231Sdim assertIsChecked(); 609303231Sdim 610303231Sdim if (compareThisIfSameType(*this, Other)) 611303231Sdim return; 612303231Sdim 613303231Sdim this->~Expected(); 614303231Sdim new (this) Expected(std::move(Other)); 615303231Sdim } 616303231Sdim 617303231Sdim pointer toPointer(pointer Val) { return Val; } 618303231Sdim 619303231Sdim const_pointer toPointer(const_pointer Val) const { return Val; } 620303231Sdim 621303231Sdim pointer toPointer(wrap *Val) { return &Val->get(); } 622303231Sdim 623303231Sdim const_pointer toPointer(const wrap *Val) const { return &Val->get(); } 624303231Sdim 625303231Sdim storage_type *getStorage() { 626303231Sdim assert(!HasError && "Cannot get value when an error exists!"); 627303231Sdim return reinterpret_cast<storage_type *>(TStorage.buffer); 628303231Sdim } 629303231Sdim 630303231Sdim const storage_type *getStorage() const { 631303231Sdim assert(!HasError && "Cannot get value when an error exists!"); 632303231Sdim return reinterpret_cast<const storage_type *>(TStorage.buffer); 633303231Sdim } 634303231Sdim 635303231Sdim error_type *getErrorStorage() { 636303231Sdim assert(HasError && "Cannot get error when a value exists!"); 637303231Sdim return reinterpret_cast<error_type *>(ErrorStorage.buffer); 638303231Sdim } 639303231Sdim 640321369Sdim const error_type *getErrorStorage() const { 641321369Sdim assert(HasError && "Cannot get error when a value exists!"); 642321369Sdim return reinterpret_cast<const error_type *>(ErrorStorage.buffer); 643321369Sdim } 644321369Sdim 645321369Sdim // Used by ExpectedAsOutParameter to reset the checked flag. 646321369Sdim void setUnchecked() { 647321369Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 648321369Sdim Unchecked = true; 649321369Sdim#endif 650321369Sdim } 651321369Sdim 652327952Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 653327952Sdim LLVM_ATTRIBUTE_NORETURN 654327952Sdim LLVM_ATTRIBUTE_NOINLINE 655327952Sdim void fatalUncheckedExpected() const { 656327952Sdim dbgs() << "Expected<T> must be checked before access or destruction.\n"; 657327952Sdim if (HasError) { 658327952Sdim dbgs() << "Unchecked Expected<T> contained error:\n"; 659327952Sdim (*getErrorStorage())->log(dbgs()); 660327952Sdim } else 661327952Sdim dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " 662327952Sdim "values in success mode must still be checked prior to being " 663327952Sdim "destroyed).\n"; 664327952Sdim abort(); 665327952Sdim } 666327952Sdim#endif 667327952Sdim 668303231Sdim void assertIsChecked() { 669314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 670327952Sdim if (LLVM_UNLIKELY(Unchecked)) 671327952Sdim fatalUncheckedExpected(); 672303231Sdim#endif 673303231Sdim } 674303231Sdim 675303231Sdim union { 676303231Sdim AlignedCharArrayUnion<storage_type> TStorage; 677303231Sdim AlignedCharArrayUnion<error_type> ErrorStorage; 678303231Sdim }; 679303231Sdim bool HasError : 1; 680314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS 681314564Sdim bool Unchecked : 1; 682303231Sdim#endif 683303231Sdim}; 684303231Sdim 685327952Sdim/// Report a serious error, calling any installed error handler. See 686327952Sdim/// ErrorHandling.h. 687327952SdimLLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, 688327952Sdim bool gen_crash_diag = true); 689327952Sdim 690327952Sdim/// Report a fatal error if Err is a failure value. 691327952Sdim/// 692327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it 693327952Sdim/// is known that the Error will always be a success value. E.g. 694327952Sdim/// 695327952Sdim/// @code{.cpp} 696327952Sdim/// // foo only attempts the fallible operation if DoFallibleOperation is 697327952Sdim/// // true. If DoFallibleOperation is false then foo always returns 698327952Sdim/// // Error::success(). 699327952Sdim/// Error foo(bool DoFallibleOperation); 700327952Sdim/// 701327952Sdim/// cantFail(foo(false)); 702327952Sdim/// @endcode 703327952Sdiminline void cantFail(Error Err, const char *Msg = nullptr) { 704327952Sdim if (Err) { 705327952Sdim if (!Msg) 706327952Sdim Msg = "Failure value returned from cantFail wrapped call"; 707327952Sdim llvm_unreachable(Msg); 708327952Sdim } 709327952Sdim} 710327952Sdim 711327952Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and 712327952Sdim/// returns the contained value. 713327952Sdim/// 714327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it 715327952Sdim/// is known that the Error will always be a success value. E.g. 716327952Sdim/// 717327952Sdim/// @code{.cpp} 718327952Sdim/// // foo only attempts the fallible operation if DoFallibleOperation is 719327952Sdim/// // true. If DoFallibleOperation is false then foo always returns an int. 720327952Sdim/// Expected<int> foo(bool DoFallibleOperation); 721327952Sdim/// 722327952Sdim/// int X = cantFail(foo(false)); 723327952Sdim/// @endcode 724327952Sdimtemplate <typename T> 725327952SdimT cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { 726327952Sdim if (ValOrErr) 727327952Sdim return std::move(*ValOrErr); 728327952Sdim else { 729327952Sdim if (!Msg) 730327952Sdim Msg = "Failure value returned from cantFail wrapped call"; 731327952Sdim llvm_unreachable(Msg); 732327952Sdim } 733327952Sdim} 734327952Sdim 735327952Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and 736327952Sdim/// returns the contained reference. 737327952Sdim/// 738327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it 739327952Sdim/// is known that the Error will always be a success value. E.g. 740327952Sdim/// 741327952Sdim/// @code{.cpp} 742327952Sdim/// // foo only attempts the fallible operation if DoFallibleOperation is 743327952Sdim/// // true. If DoFallibleOperation is false then foo always returns a Bar&. 744327952Sdim/// Expected<Bar&> foo(bool DoFallibleOperation); 745327952Sdim/// 746327952Sdim/// Bar &X = cantFail(foo(false)); 747327952Sdim/// @endcode 748327952Sdimtemplate <typename T> 749327952SdimT& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { 750327952Sdim if (ValOrErr) 751327952Sdim return *ValOrErr; 752327952Sdim else { 753327952Sdim if (!Msg) 754327952Sdim Msg = "Failure value returned from cantFail wrapped call"; 755327952Sdim llvm_unreachable(Msg); 756327952Sdim } 757327952Sdim} 758327952Sdim 759327952Sdim/// Helper for testing applicability of, and applying, handlers for 760327952Sdim/// ErrorInfo types. 761327952Sdimtemplate <typename HandlerT> 762327952Sdimclass ErrorHandlerTraits 763327952Sdim : public ErrorHandlerTraits<decltype( 764327952Sdim &std::remove_reference<HandlerT>::type::operator())> {}; 765327952Sdim 766327952Sdim// Specialization functions of the form 'Error (const ErrT&)'. 767327952Sdimtemplate <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { 768327952Sdimpublic: 769327952Sdim static bool appliesTo(const ErrorInfoBase &E) { 770327952Sdim return E.template isA<ErrT>(); 771327952Sdim } 772327952Sdim 773327952Sdim template <typename HandlerT> 774327952Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 775327952Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 776327952Sdim return H(static_cast<ErrT &>(*E)); 777327952Sdim } 778327952Sdim}; 779327952Sdim 780327952Sdim// Specialization functions of the form 'void (const ErrT&)'. 781327952Sdimtemplate <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { 782327952Sdimpublic: 783327952Sdim static bool appliesTo(const ErrorInfoBase &E) { 784327952Sdim return E.template isA<ErrT>(); 785327952Sdim } 786327952Sdim 787327952Sdim template <typename HandlerT> 788327952Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 789327952Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 790327952Sdim H(static_cast<ErrT &>(*E)); 791327952Sdim return Error::success(); 792327952Sdim } 793327952Sdim}; 794327952Sdim 795327952Sdim/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. 796327952Sdimtemplate <typename ErrT> 797327952Sdimclass ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { 798327952Sdimpublic: 799327952Sdim static bool appliesTo(const ErrorInfoBase &E) { 800327952Sdim return E.template isA<ErrT>(); 801327952Sdim } 802327952Sdim 803327952Sdim template <typename HandlerT> 804327952Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 805327952Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 806327952Sdim std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); 807327952Sdim return H(std::move(SubE)); 808327952Sdim } 809327952Sdim}; 810327952Sdim 811327952Sdim/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. 812327952Sdimtemplate <typename ErrT> 813327952Sdimclass ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { 814327952Sdimpublic: 815327952Sdim static bool appliesTo(const ErrorInfoBase &E) { 816327952Sdim return E.template isA<ErrT>(); 817327952Sdim } 818327952Sdim 819327952Sdim template <typename HandlerT> 820327952Sdim static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { 821327952Sdim assert(appliesTo(*E) && "Applying incorrect handler"); 822327952Sdim std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); 823327952Sdim H(std::move(SubE)); 824327952Sdim return Error::success(); 825327952Sdim } 826327952Sdim}; 827327952Sdim 828327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'. 829327952Sdimtemplate <typename C, typename RetT, typename ErrT> 830327952Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &)> 831327952Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 832327952Sdim 833327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'. 834327952Sdimtemplate <typename C, typename RetT, typename ErrT> 835327952Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &) const> 836327952Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 837327952Sdim 838327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'. 839327952Sdimtemplate <typename C, typename RetT, typename ErrT> 840327952Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &)> 841327952Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 842327952Sdim 843327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'. 844327952Sdimtemplate <typename C, typename RetT, typename ErrT> 845327952Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> 846327952Sdim : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; 847327952Sdim 848327952Sdim/// Specialization for member functions of the form 849327952Sdim/// 'RetT (std::unique_ptr<ErrT>)'. 850327952Sdimtemplate <typename C, typename RetT, typename ErrT> 851327952Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> 852327952Sdim : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; 853327952Sdim 854327952Sdim/// Specialization for member functions of the form 855327952Sdim/// 'RetT (std::unique_ptr<ErrT>) const'. 856327952Sdimtemplate <typename C, typename RetT, typename ErrT> 857327952Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> 858327952Sdim : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; 859327952Sdim 860327952Sdiminline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { 861327952Sdim return Error(std::move(Payload)); 862327952Sdim} 863327952Sdim 864327952Sdimtemplate <typename HandlerT, typename... HandlerTs> 865327952SdimError handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, 866327952Sdim HandlerT &&Handler, HandlerTs &&... Handlers) { 867327952Sdim if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) 868327952Sdim return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), 869327952Sdim std::move(Payload)); 870327952Sdim return handleErrorImpl(std::move(Payload), 871327952Sdim std::forward<HandlerTs>(Handlers)...); 872327952Sdim} 873327952Sdim 874327952Sdim/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any 875327952Sdim/// unhandled errors (or Errors returned by handlers) are re-concatenated and 876327952Sdim/// returned. 877327952Sdim/// Because this function returns an error, its result must also be checked 878327952Sdim/// or returned. If you intend to handle all errors use handleAllErrors 879327952Sdim/// (which returns void, and will abort() on unhandled errors) instead. 880327952Sdimtemplate <typename... HandlerTs> 881327952SdimError handleErrors(Error E, HandlerTs &&... Hs) { 882327952Sdim if (!E) 883327952Sdim return Error::success(); 884327952Sdim 885327952Sdim std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); 886327952Sdim 887327952Sdim if (Payload->isA<ErrorList>()) { 888327952Sdim ErrorList &List = static_cast<ErrorList &>(*Payload); 889327952Sdim Error R; 890327952Sdim for (auto &P : List.Payloads) 891327952Sdim R = ErrorList::join( 892327952Sdim std::move(R), 893327952Sdim handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); 894327952Sdim return R; 895327952Sdim } 896327952Sdim 897327952Sdim return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); 898327952Sdim} 899327952Sdim 900341825Sdim/// Behaves the same as handleErrors, except that by contract all errors 901341825Sdim/// *must* be handled by the given handlers (i.e. there must be no remaining 902341825Sdim/// errors after running the handlers, or llvm_unreachable is called). 903327952Sdimtemplate <typename... HandlerTs> 904327952Sdimvoid handleAllErrors(Error E, HandlerTs &&... Handlers) { 905327952Sdim cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); 906327952Sdim} 907327952Sdim 908327952Sdim/// Check that E is a non-error, then drop it. 909341825Sdim/// If E is an error, llvm_unreachable will be called. 910327952Sdiminline void handleAllErrors(Error E) { 911327952Sdim cantFail(std::move(E)); 912327952Sdim} 913327952Sdim 914327952Sdim/// Handle any errors (if present) in an Expected<T>, then try a recovery path. 915327952Sdim/// 916327952Sdim/// If the incoming value is a success value it is returned unmodified. If it 917327952Sdim/// is a failure value then it the contained error is passed to handleErrors. 918327952Sdim/// If handleErrors is able to handle the error then the RecoveryPath functor 919327952Sdim/// is called to supply the final result. If handleErrors is not able to 920327952Sdim/// handle all errors then the unhandled errors are returned. 921327952Sdim/// 922327952Sdim/// This utility enables the follow pattern: 923327952Sdim/// 924327952Sdim/// @code{.cpp} 925327952Sdim/// enum FooStrategy { Aggressive, Conservative }; 926327952Sdim/// Expected<Foo> foo(FooStrategy S); 927327952Sdim/// 928327952Sdim/// auto ResultOrErr = 929327952Sdim/// handleExpected( 930327952Sdim/// foo(Aggressive), 931327952Sdim/// []() { return foo(Conservative); }, 932327952Sdim/// [](AggressiveStrategyError&) { 933327952Sdim/// // Implicitly conusme this - we'll recover by using a conservative 934327952Sdim/// // strategy. 935327952Sdim/// }); 936327952Sdim/// 937327952Sdim/// @endcode 938327952Sdimtemplate <typename T, typename RecoveryFtor, typename... HandlerTs> 939327952SdimExpected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, 940327952Sdim HandlerTs &&... Handlers) { 941327952Sdim if (ValOrErr) 942327952Sdim return ValOrErr; 943327952Sdim 944327952Sdim if (auto Err = handleErrors(ValOrErr.takeError(), 945327952Sdim std::forward<HandlerTs>(Handlers)...)) 946327952Sdim return std::move(Err); 947327952Sdim 948327952Sdim return RecoveryPath(); 949327952Sdim} 950327952Sdim 951327952Sdim/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner 952327952Sdim/// will be printed before the first one is logged. A newline will be printed 953327952Sdim/// after each error. 954327952Sdim/// 955344779Sdim/// This function is compatible with the helpers from Support/WithColor.h. You 956344779Sdim/// can pass any of them as the OS. Please consider using them instead of 957344779Sdim/// including 'error: ' in the ErrorBanner. 958344779Sdim/// 959327952Sdim/// This is useful in the base level of your program to allow clean termination 960327952Sdim/// (allowing clean deallocation of resources, etc.), while reporting error 961327952Sdim/// information to the user. 962344779Sdimvoid logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); 963327952Sdim 964327952Sdim/// Write all error messages (if any) in E to a string. The newline character 965327952Sdim/// is used to separate error messages. 966327952Sdiminline std::string toString(Error E) { 967327952Sdim SmallVector<std::string, 2> Errors; 968327952Sdim handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { 969327952Sdim Errors.push_back(EI.message()); 970327952Sdim }); 971327952Sdim return join(Errors.begin(), Errors.end(), "\n"); 972327952Sdim} 973327952Sdim 974327952Sdim/// Consume a Error without doing anything. This method should be used 975327952Sdim/// only where an error can be considered a reasonable and expected return 976327952Sdim/// value. 977327952Sdim/// 978327952Sdim/// Uses of this method are potentially indicative of design problems: If it's 979327952Sdim/// legitimate to do nothing while processing an "error", the error-producer 980327952Sdim/// might be more clearly refactored to return an Optional<T>. 981327952Sdiminline void consumeError(Error Err) { 982327952Sdim handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); 983327952Sdim} 984327952Sdim 985341825Sdim/// Helper for converting an Error to a bool. 986341825Sdim/// 987341825Sdim/// This method returns true if Err is in an error state, or false if it is 988341825Sdim/// in a success state. Puts Err in a checked state in both cases (unlike 989341825Sdim/// Error::operator bool(), which only does this for success states). 990341825Sdiminline bool errorToBool(Error Err) { 991341825Sdim bool IsError = static_cast<bool>(Err); 992341825Sdim if (IsError) 993341825Sdim consumeError(std::move(Err)); 994341825Sdim return IsError; 995341825Sdim} 996341825Sdim 997327952Sdim/// Helper for Errors used as out-parameters. 998327952Sdim/// 999327952Sdim/// This helper is for use with the Error-as-out-parameter idiom, where an error 1000327952Sdim/// is passed to a function or method by reference, rather than being returned. 1001327952Sdim/// In such cases it is helpful to set the checked bit on entry to the function 1002327952Sdim/// so that the error can be written to (unchecked Errors abort on assignment) 1003327952Sdim/// and clear the checked bit on exit so that clients cannot accidentally forget 1004327952Sdim/// to check the result. This helper performs these actions automatically using 1005327952Sdim/// RAII: 1006327952Sdim/// 1007327952Sdim/// @code{.cpp} 1008327952Sdim/// Result foo(Error &Err) { 1009327952Sdim/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set 1010327952Sdim/// // <body of foo> 1011327952Sdim/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. 1012327952Sdim/// } 1013327952Sdim/// @endcode 1014327952Sdim/// 1015327952Sdim/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be 1016327952Sdim/// used with optional Errors (Error pointers that are allowed to be null). If 1017327952Sdim/// ErrorAsOutParameter took an Error reference, an instance would have to be 1018327952Sdim/// created inside every condition that verified that Error was non-null. By 1019327952Sdim/// taking an Error pointer we can just create one instance at the top of the 1020327952Sdim/// function. 1021327952Sdimclass ErrorAsOutParameter { 1022327952Sdimpublic: 1023327952Sdim ErrorAsOutParameter(Error *Err) : Err(Err) { 1024327952Sdim // Raise the checked bit if Err is success. 1025327952Sdim if (Err) 1026327952Sdim (void)!!*Err; 1027327952Sdim } 1028327952Sdim 1029327952Sdim ~ErrorAsOutParameter() { 1030327952Sdim // Clear the checked bit. 1031327952Sdim if (Err && !*Err) 1032327952Sdim *Err = Error::success(); 1033327952Sdim } 1034327952Sdim 1035327952Sdimprivate: 1036327952Sdim Error *Err; 1037327952Sdim}; 1038327952Sdim 1039321369Sdim/// Helper for Expected<T>s used as out-parameters. 1040321369Sdim/// 1041321369Sdim/// See ErrorAsOutParameter. 1042321369Sdimtemplate <typename T> 1043321369Sdimclass ExpectedAsOutParameter { 1044321369Sdimpublic: 1045321369Sdim ExpectedAsOutParameter(Expected<T> *ValOrErr) 1046321369Sdim : ValOrErr(ValOrErr) { 1047321369Sdim if (ValOrErr) 1048321369Sdim (void)!!*ValOrErr; 1049321369Sdim } 1050321369Sdim 1051321369Sdim ~ExpectedAsOutParameter() { 1052321369Sdim if (ValOrErr) 1053321369Sdim ValOrErr->setUnchecked(); 1054321369Sdim } 1055321369Sdim 1056321369Sdimprivate: 1057321369Sdim Expected<T> *ValOrErr; 1058321369Sdim}; 1059321369Sdim 1060303231Sdim/// This class wraps a std::error_code in a Error. 1061303231Sdim/// 1062303231Sdim/// This is useful if you're writing an interface that returns a Error 1063303231Sdim/// (or Expected) and you want to call code that still returns 1064303231Sdim/// std::error_codes. 1065303231Sdimclass ECError : public ErrorInfo<ECError> { 1066303231Sdim friend Error errorCodeToError(std::error_code); 1067314564Sdim 1068344779Sdim virtual void anchor() override; 1069344779Sdim 1070303231Sdimpublic: 1071303231Sdim void setErrorCode(std::error_code EC) { this->EC = EC; } 1072303231Sdim std::error_code convertToErrorCode() const override { return EC; } 1073303231Sdim void log(raw_ostream &OS) const override { OS << EC.message(); } 1074303231Sdim 1075303231Sdim // Used by ErrorInfo::classID. 1076303231Sdim static char ID; 1077303231Sdim 1078303231Sdimprotected: 1079303231Sdim ECError() = default; 1080303231Sdim ECError(std::error_code EC) : EC(EC) {} 1081314564Sdim 1082303231Sdim std::error_code EC; 1083303231Sdim}; 1084303231Sdim 1085303231Sdim/// The value returned by this function can be returned from convertToErrorCode 1086303231Sdim/// for Error values where no sensible translation to std::error_code exists. 1087303231Sdim/// It should only be used in this situation, and should never be used where a 1088303231Sdim/// sensible conversion to std::error_code is available, as attempts to convert 1089303231Sdim/// to/from this error will result in a fatal error. (i.e. it is a programmatic 1090303231Sdim///error to try to convert such a value). 1091303231Sdimstd::error_code inconvertibleErrorCode(); 1092303231Sdim 1093303231Sdim/// Helper for converting an std::error_code to a Error. 1094303231SdimError errorCodeToError(std::error_code EC); 1095303231Sdim 1096303231Sdim/// Helper for converting an ECError to a std::error_code. 1097303231Sdim/// 1098303231Sdim/// This method requires that Err be Error() or an ECError, otherwise it 1099303231Sdim/// will trigger a call to abort(). 1100303231Sdimstd::error_code errorToErrorCode(Error Err); 1101303231Sdim 1102303231Sdim/// Convert an ErrorOr<T> to an Expected<T>. 1103303231Sdimtemplate <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { 1104303231Sdim if (auto EC = EO.getError()) 1105303231Sdim return errorCodeToError(EC); 1106303231Sdim return std::move(*EO); 1107303231Sdim} 1108303231Sdim 1109303231Sdim/// Convert an Expected<T> to an ErrorOr<T>. 1110303231Sdimtemplate <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { 1111303231Sdim if (auto Err = E.takeError()) 1112303231Sdim return errorToErrorCode(std::move(Err)); 1113303231Sdim return std::move(*E); 1114303231Sdim} 1115303231Sdim 1116303231Sdim/// This class wraps a string in an Error. 1117303231Sdim/// 1118303231Sdim/// StringError is useful in cases where the client is not expected to be able 1119303231Sdim/// to consume the specific error message programmatically (for example, if the 1120303231Sdim/// error message is to be presented to the user). 1121344779Sdim/// 1122344779Sdim/// StringError can also be used when additional information is to be printed 1123344779Sdim/// along with a error_code message. Depending on the constructor called, this 1124344779Sdim/// class can either display: 1125344779Sdim/// 1. the error_code message (ECError behavior) 1126344779Sdim/// 2. a string 1127344779Sdim/// 3. the error_code message and a string 1128344779Sdim/// 1129344779Sdim/// These behaviors are useful when subtyping is required; for example, when a 1130344779Sdim/// specific library needs an explicit error type. In the example below, 1131344779Sdim/// PDBError is derived from StringError: 1132344779Sdim/// 1133344779Sdim/// @code{.cpp} 1134344779Sdim/// Expected<int> foo() { 1135344779Sdim/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, 1136344779Sdim/// "Additional information"); 1137344779Sdim/// } 1138344779Sdim/// @endcode 1139344779Sdim/// 1140303231Sdimclass StringError : public ErrorInfo<StringError> { 1141303231Sdimpublic: 1142303231Sdim static char ID; 1143314564Sdim 1144344779Sdim // Prints EC + S and converts to EC 1145344779Sdim StringError(std::error_code EC, const Twine &S = Twine()); 1146344779Sdim 1147344779Sdim // Prints S and converts to EC 1148303231Sdim StringError(const Twine &S, std::error_code EC); 1149314564Sdim 1150303231Sdim void log(raw_ostream &OS) const override; 1151303231Sdim std::error_code convertToErrorCode() const override; 1152314564Sdim 1153321369Sdim const std::string &getMessage() const { return Msg; } 1154321369Sdim 1155303231Sdimprivate: 1156303231Sdim std::string Msg; 1157303231Sdim std::error_code EC; 1158344779Sdim const bool PrintMsgOnly = false; 1159303231Sdim}; 1160303231Sdim 1161341825Sdim/// Create formatted StringError object. 1162341825Sdimtemplate <typename... Ts> 1163353358Sdiminline Error createStringError(std::error_code EC, char const *Fmt, 1164353358Sdim const Ts &... Vals) { 1165341825Sdim std::string Buffer; 1166341825Sdim raw_string_ostream Stream(Buffer); 1167341825Sdim Stream << format(Fmt, Vals...); 1168341825Sdim return make_error<StringError>(Stream.str(), EC); 1169341825Sdim} 1170341825Sdim 1171341825SdimError createStringError(std::error_code EC, char const *Msg); 1172341825Sdim 1173353358Sdimtemplate <typename... Ts> 1174353358Sdiminline Error createStringError(std::errc EC, char const *Fmt, 1175353358Sdim const Ts &... Vals) { 1176353358Sdim return createStringError(std::make_error_code(EC), Fmt, Vals...); 1177353358Sdim} 1178353358Sdim 1179344779Sdim/// This class wraps a filename and another Error. 1180344779Sdim/// 1181344779Sdim/// In some cases, an error needs to live along a 'source' name, in order to 1182344779Sdim/// show more detailed information to the user. 1183344779Sdimclass FileError final : public ErrorInfo<FileError> { 1184344779Sdim 1185353358Sdim friend Error createFileError(const Twine &, Error); 1186353358Sdim friend Error createFileError(const Twine &, size_t, Error); 1187344779Sdim 1188344779Sdimpublic: 1189344779Sdim void log(raw_ostream &OS) const override { 1190344779Sdim assert(Err && !FileName.empty() && "Trying to log after takeError()."); 1191344779Sdim OS << "'" << FileName << "': "; 1192353358Sdim if (Line.hasValue()) 1193353358Sdim OS << "line " << Line.getValue() << ": "; 1194344779Sdim Err->log(OS); 1195344779Sdim } 1196344779Sdim 1197344779Sdim Error takeError() { return Error(std::move(Err)); } 1198344779Sdim 1199344779Sdim std::error_code convertToErrorCode() const override; 1200344779Sdim 1201344779Sdim // Used by ErrorInfo::classID. 1202344779Sdim static char ID; 1203344779Sdim 1204344779Sdimprivate: 1205353358Sdim FileError(const Twine &F, Optional<size_t> LineNum, 1206353358Sdim std::unique_ptr<ErrorInfoBase> E) { 1207344779Sdim assert(E && "Cannot create FileError from Error success value."); 1208353358Sdim assert(!F.isTriviallyEmpty() && 1209344779Sdim "The file name provided to FileError must not be empty."); 1210353358Sdim FileName = F.str(); 1211344779Sdim Err = std::move(E); 1212353358Sdim Line = std::move(LineNum); 1213344779Sdim } 1214344779Sdim 1215353358Sdim static Error build(const Twine &F, Optional<size_t> Line, Error E) { 1216353358Sdim return Error( 1217353358Sdim std::unique_ptr<FileError>(new FileError(F, Line, E.takePayload()))); 1218344779Sdim } 1219344779Sdim 1220344779Sdim std::string FileName; 1221353358Sdim Optional<size_t> Line; 1222344779Sdim std::unique_ptr<ErrorInfoBase> Err; 1223344779Sdim}; 1224344779Sdim 1225344779Sdim/// Concatenate a source file path and/or name with an Error. The resulting 1226344779Sdim/// Error is unchecked. 1227353358Sdiminline Error createFileError(const Twine &F, Error E) { 1228353358Sdim return FileError::build(F, Optional<size_t>(), std::move(E)); 1229344779Sdim} 1230344779Sdim 1231353358Sdim/// Concatenate a source file path and/or name with line number and an Error. 1232353358Sdim/// The resulting Error is unchecked. 1233353358Sdiminline Error createFileError(const Twine &F, size_t Line, Error E) { 1234353358Sdim return FileError::build(F, Optional<size_t>(Line), std::move(E)); 1235353358Sdim} 1236344779Sdim 1237353358Sdim/// Concatenate a source file path and/or name with a std::error_code 1238353358Sdim/// to form an Error object. 1239353358Sdiminline Error createFileError(const Twine &F, std::error_code EC) { 1240353358Sdim return createFileError(F, errorCodeToError(EC)); 1241353358Sdim} 1242353358Sdim 1243353358Sdim/// Concatenate a source file path and/or name with line number and 1244353358Sdim/// std::error_code to form an Error object. 1245353358Sdiminline Error createFileError(const Twine &F, size_t Line, std::error_code EC) { 1246353358Sdim return createFileError(F, Line, errorCodeToError(EC)); 1247353358Sdim} 1248353358Sdim 1249353358SdimError createFileError(const Twine &F, ErrorSuccess) = delete; 1250353358Sdim 1251303231Sdim/// Helper for check-and-exit error handling. 1252303231Sdim/// 1253303231Sdim/// For tool use only. NOT FOR USE IN LIBRARY CODE. 1254303231Sdim/// 1255303231Sdimclass ExitOnError { 1256303231Sdimpublic: 1257303231Sdim /// Create an error on exit helper. 1258303231Sdim ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) 1259303231Sdim : Banner(std::move(Banner)), 1260303231Sdim GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} 1261303231Sdim 1262303231Sdim /// Set the banner string for any errors caught by operator(). 1263303231Sdim void setBanner(std::string Banner) { this->Banner = std::move(Banner); } 1264303231Sdim 1265303231Sdim /// Set the exit-code mapper function. 1266303231Sdim void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { 1267303231Sdim this->GetExitCode = std::move(GetExitCode); 1268303231Sdim } 1269303231Sdim 1270303231Sdim /// Check Err. If it's in a failure state log the error(s) and exit. 1271303231Sdim void operator()(Error Err) const { checkError(std::move(Err)); } 1272303231Sdim 1273303231Sdim /// Check E. If it's in a success state then return the contained value. If 1274303231Sdim /// it's in a failure state log the error(s) and exit. 1275303231Sdim template <typename T> T operator()(Expected<T> &&E) const { 1276303231Sdim checkError(E.takeError()); 1277303231Sdim return std::move(*E); 1278303231Sdim } 1279303231Sdim 1280303231Sdim /// Check E. If it's in a success state then return the contained reference. If 1281303231Sdim /// it's in a failure state log the error(s) and exit. 1282303231Sdim template <typename T> T& operator()(Expected<T&> &&E) const { 1283303231Sdim checkError(E.takeError()); 1284303231Sdim return *E; 1285303231Sdim } 1286303231Sdim 1287303231Sdimprivate: 1288303231Sdim void checkError(Error Err) const { 1289303231Sdim if (Err) { 1290303231Sdim int ExitCode = GetExitCode(Err); 1291303231Sdim logAllUnhandledErrors(std::move(Err), errs(), Banner); 1292303231Sdim exit(ExitCode); 1293303231Sdim } 1294303231Sdim } 1295303231Sdim 1296303231Sdim std::string Banner; 1297303231Sdim std::function<int(const Error &)> GetExitCode; 1298303231Sdim}; 1299303231Sdim 1300344779Sdim/// Conversion from Error to LLVMErrorRef for C error bindings. 1301344779Sdiminline LLVMErrorRef wrap(Error Err) { 1302344779Sdim return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); 1303344779Sdim} 1304344779Sdim 1305344779Sdim/// Conversion from LLVMErrorRef to Error for C error bindings. 1306344779Sdiminline Error unwrap(LLVMErrorRef ErrRef) { 1307344779Sdim return Error(std::unique_ptr<ErrorInfoBase>( 1308344779Sdim reinterpret_cast<ErrorInfoBase *>(ErrRef))); 1309344779Sdim} 1310344779Sdim 1311314564Sdim} // end namespace llvm 1312303231Sdim 1313303231Sdim#endif // LLVM_SUPPORT_ERROR_H 1314