Error.h revision 327952
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:
249327952Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
250327952Sdim  // assertIsChecked() happens very frequently, but under normal circumstances
251327952Sdim  // is supposed to be a no-op.  So we want it to be inlined, but having a bunch
252327952Sdim  // of debug prints can cause the function to be too large for inlining.  So
253327952Sdim  // it's important that we define this function out of line so that it can't be
254327952Sdim  // inlined.
255327952Sdim  LLVM_ATTRIBUTE_NORETURN
256327952Sdim  void fatalUncheckedError() const;
257327952Sdim#endif
258327952Sdim
259303231Sdim  void assertIsChecked() {
260314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
261327952Sdim    if (LLVM_UNLIKELY(!getChecked() || getPtr()))
262327952Sdim      fatalUncheckedError();
263303231Sdim#endif
264303231Sdim  }
265303231Sdim
266303231Sdim  ErrorInfoBase *getPtr() const {
267314564Sdim    return reinterpret_cast<ErrorInfoBase*>(
268314564Sdim             reinterpret_cast<uintptr_t>(Payload) &
269314564Sdim             ~static_cast<uintptr_t>(0x1));
270303231Sdim  }
271303231Sdim
272303231Sdim  void setPtr(ErrorInfoBase *EI) {
273314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
274314564Sdim    Payload = reinterpret_cast<ErrorInfoBase*>(
275314564Sdim                (reinterpret_cast<uintptr_t>(EI) &
276314564Sdim                 ~static_cast<uintptr_t>(0x1)) |
277314564Sdim                (reinterpret_cast<uintptr_t>(Payload) & 0x1));
278303231Sdim#else
279303231Sdim    Payload = EI;
280303231Sdim#endif
281303231Sdim  }
282303231Sdim
283303231Sdim  bool getChecked() const {
284314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
285314564Sdim    return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
286303231Sdim#else
287303231Sdim    return true;
288303231Sdim#endif
289303231Sdim  }
290303231Sdim
291303231Sdim  void setChecked(bool V) {
292314564Sdim    Payload = reinterpret_cast<ErrorInfoBase*>(
293314564Sdim                (reinterpret_cast<uintptr_t>(Payload) &
294314564Sdim                  ~static_cast<uintptr_t>(0x1)) |
295314564Sdim                  (V ? 0 : 1));
296303231Sdim  }
297303231Sdim
298303231Sdim  std::unique_ptr<ErrorInfoBase> takePayload() {
299303231Sdim    std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
300303231Sdim    setPtr(nullptr);
301303231Sdim    setChecked(true);
302303231Sdim    return Tmp;
303303231Sdim  }
304303231Sdim
305321369Sdim  ErrorInfoBase *Payload = nullptr;
306303231Sdim};
307303231Sdim
308314564Sdim/// Subclass of Error for the sole purpose of identifying the success path in
309314564Sdim/// the type system. This allows to catch invalid conversion to Expected<T> at
310314564Sdim/// compile time.
311314564Sdimclass ErrorSuccess : public Error {};
312314564Sdim
313314564Sdiminline ErrorSuccess Error::success() { return ErrorSuccess(); }
314314564Sdim
315303231Sdim/// Make a Error instance representing failure using the given error info
316303231Sdim/// type.
317303231Sdimtemplate <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
318303231Sdim  return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
319303231Sdim}
320303231Sdim
321303231Sdim/// Base class for user error types. Users should declare their error types
322303231Sdim/// like:
323303231Sdim///
324303231Sdim/// class MyError : public ErrorInfo<MyError> {
325303231Sdim///   ....
326303231Sdim/// };
327303231Sdim///
328303231Sdim/// This class provides an implementation of the ErrorInfoBase::kind
329303231Sdim/// method, which is used by the Error RTTI system.
330303231Sdimtemplate <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
331303231Sdimclass ErrorInfo : public ParentErrT {
332303231Sdimpublic:
333321369Sdim  static const void *classID() { return &ThisErrT::ID; }
334321369Sdim
335321369Sdim  const void *dynamicClassID() const override { return &ThisErrT::ID; }
336321369Sdim
337303231Sdim  bool isA(const void *const ClassID) const override {
338303231Sdim    return ClassID == classID() || ParentErrT::isA(ClassID);
339303231Sdim  }
340303231Sdim};
341303231Sdim
342303231Sdim/// Special ErrorInfo subclass representing a list of ErrorInfos.
343303231Sdim/// Instances of this class are constructed by joinError.
344303231Sdimclass ErrorList final : public ErrorInfo<ErrorList> {
345303231Sdim  // handleErrors needs to be able to iterate the payload list of an
346303231Sdim  // ErrorList.
347303231Sdim  template <typename... HandlerTs>
348303231Sdim  friend Error handleErrors(Error E, HandlerTs &&... Handlers);
349303231Sdim
350303231Sdim  // joinErrors is implemented in terms of join.
351303231Sdim  friend Error joinErrors(Error, Error);
352303231Sdim
353303231Sdimpublic:
354303231Sdim  void log(raw_ostream &OS) const override {
355303231Sdim    OS << "Multiple errors:\n";
356303231Sdim    for (auto &ErrPayload : Payloads) {
357303231Sdim      ErrPayload->log(OS);
358303231Sdim      OS << "\n";
359303231Sdim    }
360303231Sdim  }
361303231Sdim
362303231Sdim  std::error_code convertToErrorCode() const override;
363303231Sdim
364303231Sdim  // Used by ErrorInfo::classID.
365303231Sdim  static char ID;
366303231Sdim
367303231Sdimprivate:
368303231Sdim  ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
369303231Sdim            std::unique_ptr<ErrorInfoBase> Payload2) {
370303231Sdim    assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
371303231Sdim           "ErrorList constructor payloads should be singleton errors");
372303231Sdim    Payloads.push_back(std::move(Payload1));
373303231Sdim    Payloads.push_back(std::move(Payload2));
374303231Sdim  }
375303231Sdim
376303231Sdim  static Error join(Error E1, Error E2) {
377303231Sdim    if (!E1)
378303231Sdim      return E2;
379303231Sdim    if (!E2)
380303231Sdim      return E1;
381303231Sdim    if (E1.isA<ErrorList>()) {
382303231Sdim      auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
383303231Sdim      if (E2.isA<ErrorList>()) {
384303231Sdim        auto E2Payload = E2.takePayload();
385303231Sdim        auto &E2List = static_cast<ErrorList &>(*E2Payload);
386303231Sdim        for (auto &Payload : E2List.Payloads)
387303231Sdim          E1List.Payloads.push_back(std::move(Payload));
388303231Sdim      } else
389303231Sdim        E1List.Payloads.push_back(E2.takePayload());
390303231Sdim
391303231Sdim      return E1;
392303231Sdim    }
393303231Sdim    if (E2.isA<ErrorList>()) {
394303231Sdim      auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
395303231Sdim      E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
396303231Sdim      return E2;
397303231Sdim    }
398303231Sdim    return Error(std::unique_ptr<ErrorList>(
399303231Sdim        new ErrorList(E1.takePayload(), E2.takePayload())));
400303231Sdim  }
401303231Sdim
402303231Sdim  std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
403303231Sdim};
404303231Sdim
405303231Sdim/// Concatenate errors. The resulting Error is unchecked, and contains the
406303231Sdim/// ErrorInfo(s), if any, contained in E1, followed by the
407303231Sdim/// ErrorInfo(s), if any, contained in E2.
408303231Sdiminline Error joinErrors(Error E1, Error E2) {
409303231Sdim  return ErrorList::join(std::move(E1), std::move(E2));
410303231Sdim}
411303231Sdim
412303231Sdim/// Tagged union holding either a T or a Error.
413303231Sdim///
414303231Sdim/// This class parallels ErrorOr, but replaces error_code with Error. Since
415303231Sdim/// Error cannot be copied, this class replaces getError() with
416303231Sdim/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
417303231Sdim/// error class type.
418314564Sdimtemplate <class T> class LLVM_NODISCARD Expected {
419321369Sdim  template <class T1> friend class ExpectedAsOutParameter;
420303231Sdim  template <class OtherT> friend class Expected;
421321369Sdim
422303231Sdim  static const bool isRef = std::is_reference<T>::value;
423303231Sdim
424321369Sdim  using wrap = ReferenceStorage<typename std::remove_reference<T>::type>;
425303231Sdim
426321369Sdim  using error_type = std::unique_ptr<ErrorInfoBase>;
427321369Sdim
428303231Sdimpublic:
429321369Sdim  using storage_type = typename std::conditional<isRef, wrap, T>::type;
430321369Sdim  using value_type = T;
431303231Sdim
432303231Sdimprivate:
433321369Sdim  using reference = typename std::remove_reference<T>::type &;
434321369Sdim  using const_reference = const typename std::remove_reference<T>::type &;
435321369Sdim  using pointer = typename std::remove_reference<T>::type *;
436321369Sdim  using const_pointer = const typename std::remove_reference<T>::type *;
437303231Sdim
438303231Sdimpublic:
439303231Sdim  /// Create an Expected<T> error value from the given Error.
440303231Sdim  Expected(Error Err)
441303231Sdim      : HasError(true)
442314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
443314564Sdim        // Expected is unchecked upon construction in Debug builds.
444314564Sdim        , Unchecked(true)
445303231Sdim#endif
446303231Sdim  {
447303231Sdim    assert(Err && "Cannot create Expected<T> from Error success value.");
448314564Sdim    new (getErrorStorage()) error_type(Err.takePayload());
449303231Sdim  }
450303231Sdim
451314564Sdim  /// Forbid to convert from Error::success() implicitly, this avoids having
452314564Sdim  /// Expected<T> foo() { return Error::success(); } which compiles otherwise
453314564Sdim  /// but triggers the assertion above.
454314564Sdim  Expected(ErrorSuccess) = delete;
455314564Sdim
456303231Sdim  /// Create an Expected<T> success value from the given OtherT value, which
457303231Sdim  /// must be convertible to T.
458303231Sdim  template <typename OtherT>
459303231Sdim  Expected(OtherT &&Val,
460303231Sdim           typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
461303231Sdim               * = nullptr)
462303231Sdim      : HasError(false)
463314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
464314564Sdim        // Expected is unchecked upon construction in Debug builds.
465314564Sdim        , Unchecked(true)
466303231Sdim#endif
467303231Sdim  {
468303231Sdim    new (getStorage()) storage_type(std::forward<OtherT>(Val));
469303231Sdim  }
470303231Sdim
471303231Sdim  /// Move construct an Expected<T> value.
472303231Sdim  Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
473303231Sdim
474303231Sdim  /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
475303231Sdim  /// must be convertible to T.
476303231Sdim  template <class OtherT>
477303231Sdim  Expected(Expected<OtherT> &&Other,
478303231Sdim           typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
479303231Sdim               * = nullptr) {
480303231Sdim    moveConstruct(std::move(Other));
481303231Sdim  }
482303231Sdim
483303231Sdim  /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
484303231Sdim  /// isn't convertible to T.
485303231Sdim  template <class OtherT>
486303231Sdim  explicit Expected(
487303231Sdim      Expected<OtherT> &&Other,
488303231Sdim      typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
489303231Sdim          nullptr) {
490303231Sdim    moveConstruct(std::move(Other));
491303231Sdim  }
492303231Sdim
493303231Sdim  /// Move-assign from another Expected<T>.
494303231Sdim  Expected &operator=(Expected &&Other) {
495303231Sdim    moveAssign(std::move(Other));
496303231Sdim    return *this;
497303231Sdim  }
498303231Sdim
499303231Sdim  /// Destroy an Expected<T>.
500303231Sdim  ~Expected() {
501303231Sdim    assertIsChecked();
502303231Sdim    if (!HasError)
503303231Sdim      getStorage()->~storage_type();
504303231Sdim    else
505303231Sdim      getErrorStorage()->~error_type();
506303231Sdim  }
507303231Sdim
508303231Sdim  /// \brief Return false if there is an error.
509303231Sdim  explicit operator bool() {
510314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
511314564Sdim    Unchecked = HasError;
512303231Sdim#endif
513303231Sdim    return !HasError;
514303231Sdim  }
515303231Sdim
516303231Sdim  /// \brief Returns a reference to the stored T value.
517303231Sdim  reference get() {
518303231Sdim    assertIsChecked();
519303231Sdim    return *getStorage();
520303231Sdim  }
521303231Sdim
522303231Sdim  /// \brief Returns a const reference to the stored T value.
523303231Sdim  const_reference get() const {
524303231Sdim    assertIsChecked();
525303231Sdim    return const_cast<Expected<T> *>(this)->get();
526303231Sdim  }
527303231Sdim
528303231Sdim  /// \brief Check that this Expected<T> is an error of type ErrT.
529303231Sdim  template <typename ErrT> bool errorIsA() const {
530321369Sdim    return HasError && (*getErrorStorage())->template isA<ErrT>();
531303231Sdim  }
532303231Sdim
533303231Sdim  /// \brief Take ownership of the stored error.
534303231Sdim  /// After calling this the Expected<T> is in an indeterminate state that can
535303231Sdim  /// only be safely destructed. No further calls (beside the destructor) should
536303231Sdim  /// be made on the Expected<T> vaule.
537303231Sdim  Error takeError() {
538314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
539314564Sdim    Unchecked = false;
540303231Sdim#endif
541303231Sdim    return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
542303231Sdim  }
543303231Sdim
544303231Sdim  /// \brief Returns a pointer to the stored T value.
545303231Sdim  pointer operator->() {
546303231Sdim    assertIsChecked();
547303231Sdim    return toPointer(getStorage());
548303231Sdim  }
549303231Sdim
550303231Sdim  /// \brief Returns a const pointer to the stored T value.
551303231Sdim  const_pointer operator->() const {
552303231Sdim    assertIsChecked();
553303231Sdim    return toPointer(getStorage());
554303231Sdim  }
555303231Sdim
556303231Sdim  /// \brief Returns a reference to the stored T value.
557303231Sdim  reference operator*() {
558303231Sdim    assertIsChecked();
559303231Sdim    return *getStorage();
560303231Sdim  }
561303231Sdim
562303231Sdim  /// \brief Returns a const reference to the stored T value.
563303231Sdim  const_reference operator*() const {
564303231Sdim    assertIsChecked();
565303231Sdim    return *getStorage();
566303231Sdim  }
567303231Sdim
568303231Sdimprivate:
569303231Sdim  template <class T1>
570303231Sdim  static bool compareThisIfSameType(const T1 &a, const T1 &b) {
571303231Sdim    return &a == &b;
572303231Sdim  }
573303231Sdim
574303231Sdim  template <class T1, class T2>
575303231Sdim  static bool compareThisIfSameType(const T1 &a, const T2 &b) {
576303231Sdim    return false;
577303231Sdim  }
578303231Sdim
579303231Sdim  template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
580303231Sdim    HasError = Other.HasError;
581314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
582314564Sdim    Unchecked = true;
583314564Sdim    Other.Unchecked = false;
584303231Sdim#endif
585303231Sdim
586303231Sdim    if (!HasError)
587303231Sdim      new (getStorage()) storage_type(std::move(*Other.getStorage()));
588303231Sdim    else
589303231Sdim      new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
590303231Sdim  }
591303231Sdim
592303231Sdim  template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
593303231Sdim    assertIsChecked();
594303231Sdim
595303231Sdim    if (compareThisIfSameType(*this, Other))
596303231Sdim      return;
597303231Sdim
598303231Sdim    this->~Expected();
599303231Sdim    new (this) Expected(std::move(Other));
600303231Sdim  }
601303231Sdim
602303231Sdim  pointer toPointer(pointer Val) { return Val; }
603303231Sdim
604303231Sdim  const_pointer toPointer(const_pointer Val) const { return Val; }
605303231Sdim
606303231Sdim  pointer toPointer(wrap *Val) { return &Val->get(); }
607303231Sdim
608303231Sdim  const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
609303231Sdim
610303231Sdim  storage_type *getStorage() {
611303231Sdim    assert(!HasError && "Cannot get value when an error exists!");
612303231Sdim    return reinterpret_cast<storage_type *>(TStorage.buffer);
613303231Sdim  }
614303231Sdim
615303231Sdim  const storage_type *getStorage() const {
616303231Sdim    assert(!HasError && "Cannot get value when an error exists!");
617303231Sdim    return reinterpret_cast<const storage_type *>(TStorage.buffer);
618303231Sdim  }
619303231Sdim
620303231Sdim  error_type *getErrorStorage() {
621303231Sdim    assert(HasError && "Cannot get error when a value exists!");
622303231Sdim    return reinterpret_cast<error_type *>(ErrorStorage.buffer);
623303231Sdim  }
624303231Sdim
625321369Sdim  const error_type *getErrorStorage() const {
626321369Sdim    assert(HasError && "Cannot get error when a value exists!");
627321369Sdim    return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
628321369Sdim  }
629321369Sdim
630321369Sdim  // Used by ExpectedAsOutParameter to reset the checked flag.
631321369Sdim  void setUnchecked() {
632321369Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
633321369Sdim    Unchecked = true;
634321369Sdim#endif
635321369Sdim  }
636321369Sdim
637327952Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
638327952Sdim  LLVM_ATTRIBUTE_NORETURN
639327952Sdim  LLVM_ATTRIBUTE_NOINLINE
640327952Sdim  void fatalUncheckedExpected() const {
641327952Sdim    dbgs() << "Expected<T> must be checked before access or destruction.\n";
642327952Sdim    if (HasError) {
643327952Sdim      dbgs() << "Unchecked Expected<T> contained error:\n";
644327952Sdim      (*getErrorStorage())->log(dbgs());
645327952Sdim    } else
646327952Sdim      dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
647327952Sdim                "values in success mode must still be checked prior to being "
648327952Sdim                "destroyed).\n";
649327952Sdim    abort();
650327952Sdim  }
651327952Sdim#endif
652327952Sdim
653303231Sdim  void assertIsChecked() {
654314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
655327952Sdim    if (LLVM_UNLIKELY(Unchecked))
656327952Sdim      fatalUncheckedExpected();
657303231Sdim#endif
658303231Sdim  }
659303231Sdim
660303231Sdim  union {
661303231Sdim    AlignedCharArrayUnion<storage_type> TStorage;
662303231Sdim    AlignedCharArrayUnion<error_type> ErrorStorage;
663303231Sdim  };
664303231Sdim  bool HasError : 1;
665314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
666314564Sdim  bool Unchecked : 1;
667303231Sdim#endif
668303231Sdim};
669303231Sdim
670327952Sdim/// Report a serious error, calling any installed error handler. See
671327952Sdim/// ErrorHandling.h.
672327952SdimLLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err,
673327952Sdim                                                bool gen_crash_diag = true);
674327952Sdim
675327952Sdim/// Report a fatal error if Err is a failure value.
676327952Sdim///
677327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it
678327952Sdim/// is known that the Error will always be a success value. E.g.
679327952Sdim///
680327952Sdim///   @code{.cpp}
681327952Sdim///   // foo only attempts the fallible operation if DoFallibleOperation is
682327952Sdim///   // true. If DoFallibleOperation is false then foo always returns
683327952Sdim///   // Error::success().
684327952Sdim///   Error foo(bool DoFallibleOperation);
685327952Sdim///
686327952Sdim///   cantFail(foo(false));
687327952Sdim///   @endcode
688327952Sdiminline void cantFail(Error Err, const char *Msg = nullptr) {
689327952Sdim  if (Err) {
690327952Sdim    if (!Msg)
691327952Sdim      Msg = "Failure value returned from cantFail wrapped call";
692327952Sdim    llvm_unreachable(Msg);
693327952Sdim  }
694327952Sdim}
695327952Sdim
696327952Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
697327952Sdim/// returns the contained value.
698327952Sdim///
699327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it
700327952Sdim/// is known that the Error will always be a success value. E.g.
701327952Sdim///
702327952Sdim///   @code{.cpp}
703327952Sdim///   // foo only attempts the fallible operation if DoFallibleOperation is
704327952Sdim///   // true. If DoFallibleOperation is false then foo always returns an int.
705327952Sdim///   Expected<int> foo(bool DoFallibleOperation);
706327952Sdim///
707327952Sdim///   int X = cantFail(foo(false));
708327952Sdim///   @endcode
709327952Sdimtemplate <typename T>
710327952SdimT cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
711327952Sdim  if (ValOrErr)
712327952Sdim    return std::move(*ValOrErr);
713327952Sdim  else {
714327952Sdim    if (!Msg)
715327952Sdim      Msg = "Failure value returned from cantFail wrapped call";
716327952Sdim    llvm_unreachable(Msg);
717327952Sdim  }
718327952Sdim}
719327952Sdim
720327952Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
721327952Sdim/// returns the contained reference.
722327952Sdim///
723327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it
724327952Sdim/// is known that the Error will always be a success value. E.g.
725327952Sdim///
726327952Sdim///   @code{.cpp}
727327952Sdim///   // foo only attempts the fallible operation if DoFallibleOperation is
728327952Sdim///   // true. If DoFallibleOperation is false then foo always returns a Bar&.
729327952Sdim///   Expected<Bar&> foo(bool DoFallibleOperation);
730327952Sdim///
731327952Sdim///   Bar &X = cantFail(foo(false));
732327952Sdim///   @endcode
733327952Sdimtemplate <typename T>
734327952SdimT& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
735327952Sdim  if (ValOrErr)
736327952Sdim    return *ValOrErr;
737327952Sdim  else {
738327952Sdim    if (!Msg)
739327952Sdim      Msg = "Failure value returned from cantFail wrapped call";
740327952Sdim    llvm_unreachable(Msg);
741327952Sdim  }
742327952Sdim}
743327952Sdim
744327952Sdim/// Helper for testing applicability of, and applying, handlers for
745327952Sdim/// ErrorInfo types.
746327952Sdimtemplate <typename HandlerT>
747327952Sdimclass ErrorHandlerTraits
748327952Sdim    : public ErrorHandlerTraits<decltype(
749327952Sdim          &std::remove_reference<HandlerT>::type::operator())> {};
750327952Sdim
751327952Sdim// Specialization functions of the form 'Error (const ErrT&)'.
752327952Sdimtemplate <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
753327952Sdimpublic:
754327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
755327952Sdim    return E.template isA<ErrT>();
756327952Sdim  }
757327952Sdim
758327952Sdim  template <typename HandlerT>
759327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
760327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
761327952Sdim    return H(static_cast<ErrT &>(*E));
762327952Sdim  }
763327952Sdim};
764327952Sdim
765327952Sdim// Specialization functions of the form 'void (const ErrT&)'.
766327952Sdimtemplate <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
767327952Sdimpublic:
768327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
769327952Sdim    return E.template isA<ErrT>();
770327952Sdim  }
771327952Sdim
772327952Sdim  template <typename HandlerT>
773327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
774327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
775327952Sdim    H(static_cast<ErrT &>(*E));
776327952Sdim    return Error::success();
777327952Sdim  }
778327952Sdim};
779327952Sdim
780327952Sdim/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
781327952Sdimtemplate <typename ErrT>
782327952Sdimclass ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
783327952Sdimpublic:
784327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
785327952Sdim    return E.template isA<ErrT>();
786327952Sdim  }
787327952Sdim
788327952Sdim  template <typename HandlerT>
789327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
790327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
791327952Sdim    std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
792327952Sdim    return H(std::move(SubE));
793327952Sdim  }
794327952Sdim};
795327952Sdim
796327952Sdim/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
797327952Sdimtemplate <typename ErrT>
798327952Sdimclass ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
799327952Sdimpublic:
800327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
801327952Sdim    return E.template isA<ErrT>();
802327952Sdim  }
803327952Sdim
804327952Sdim  template <typename HandlerT>
805327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
806327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
807327952Sdim    std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
808327952Sdim    H(std::move(SubE));
809327952Sdim    return Error::success();
810327952Sdim  }
811327952Sdim};
812327952Sdim
813327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'.
814327952Sdimtemplate <typename C, typename RetT, typename ErrT>
815327952Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &)>
816327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
817327952Sdim
818327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'.
819327952Sdimtemplate <typename C, typename RetT, typename ErrT>
820327952Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
821327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
822327952Sdim
823327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'.
824327952Sdimtemplate <typename C, typename RetT, typename ErrT>
825327952Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
826327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
827327952Sdim
828327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'.
829327952Sdimtemplate <typename C, typename RetT, typename ErrT>
830327952Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
831327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
832327952Sdim
833327952Sdim/// Specialization for member functions of the form
834327952Sdim/// 'RetT (std::unique_ptr<ErrT>)'.
835327952Sdimtemplate <typename C, typename RetT, typename ErrT>
836327952Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
837327952Sdim    : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
838327952Sdim
839327952Sdim/// Specialization for member functions of the form
840327952Sdim/// 'RetT (std::unique_ptr<ErrT>) const'.
841327952Sdimtemplate <typename C, typename RetT, typename ErrT>
842327952Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
843327952Sdim    : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
844327952Sdim
845327952Sdiminline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
846327952Sdim  return Error(std::move(Payload));
847327952Sdim}
848327952Sdim
849327952Sdimtemplate <typename HandlerT, typename... HandlerTs>
850327952SdimError handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
851327952Sdim                      HandlerT &&Handler, HandlerTs &&... Handlers) {
852327952Sdim  if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
853327952Sdim    return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
854327952Sdim                                               std::move(Payload));
855327952Sdim  return handleErrorImpl(std::move(Payload),
856327952Sdim                         std::forward<HandlerTs>(Handlers)...);
857327952Sdim}
858327952Sdim
859327952Sdim/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
860327952Sdim/// unhandled errors (or Errors returned by handlers) are re-concatenated and
861327952Sdim/// returned.
862327952Sdim/// Because this function returns an error, its result must also be checked
863327952Sdim/// or returned. If you intend to handle all errors use handleAllErrors
864327952Sdim/// (which returns void, and will abort() on unhandled errors) instead.
865327952Sdimtemplate <typename... HandlerTs>
866327952SdimError handleErrors(Error E, HandlerTs &&... Hs) {
867327952Sdim  if (!E)
868327952Sdim    return Error::success();
869327952Sdim
870327952Sdim  std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
871327952Sdim
872327952Sdim  if (Payload->isA<ErrorList>()) {
873327952Sdim    ErrorList &List = static_cast<ErrorList &>(*Payload);
874327952Sdim    Error R;
875327952Sdim    for (auto &P : List.Payloads)
876327952Sdim      R = ErrorList::join(
877327952Sdim          std::move(R),
878327952Sdim          handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
879327952Sdim    return R;
880327952Sdim  }
881327952Sdim
882327952Sdim  return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
883327952Sdim}
884327952Sdim
885327952Sdim/// Behaves the same as handleErrors, except that it requires that all
886327952Sdim/// errors be handled by the given handlers. If any unhandled error remains
887327952Sdim/// after the handlers have run, report_fatal_error() will be called.
888327952Sdimtemplate <typename... HandlerTs>
889327952Sdimvoid handleAllErrors(Error E, HandlerTs &&... Handlers) {
890327952Sdim  cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
891327952Sdim}
892327952Sdim
893327952Sdim/// Check that E is a non-error, then drop it.
894327952Sdim/// If E is an error report_fatal_error will be called.
895327952Sdiminline void handleAllErrors(Error E) {
896327952Sdim  cantFail(std::move(E));
897327952Sdim}
898327952Sdim
899327952Sdim/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
900327952Sdim///
901327952Sdim/// If the incoming value is a success value it is returned unmodified. If it
902327952Sdim/// is a failure value then it the contained error is passed to handleErrors.
903327952Sdim/// If handleErrors is able to handle the error then the RecoveryPath functor
904327952Sdim/// is called to supply the final result. If handleErrors is not able to
905327952Sdim/// handle all errors then the unhandled errors are returned.
906327952Sdim///
907327952Sdim/// This utility enables the follow pattern:
908327952Sdim///
909327952Sdim///   @code{.cpp}
910327952Sdim///   enum FooStrategy { Aggressive, Conservative };
911327952Sdim///   Expected<Foo> foo(FooStrategy S);
912327952Sdim///
913327952Sdim///   auto ResultOrErr =
914327952Sdim///     handleExpected(
915327952Sdim///       foo(Aggressive),
916327952Sdim///       []() { return foo(Conservative); },
917327952Sdim///       [](AggressiveStrategyError&) {
918327952Sdim///         // Implicitly conusme this - we'll recover by using a conservative
919327952Sdim///         // strategy.
920327952Sdim///       });
921327952Sdim///
922327952Sdim///   @endcode
923327952Sdimtemplate <typename T, typename RecoveryFtor, typename... HandlerTs>
924327952SdimExpected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
925327952Sdim                           HandlerTs &&... Handlers) {
926327952Sdim  if (ValOrErr)
927327952Sdim    return ValOrErr;
928327952Sdim
929327952Sdim  if (auto Err = handleErrors(ValOrErr.takeError(),
930327952Sdim                              std::forward<HandlerTs>(Handlers)...))
931327952Sdim    return std::move(Err);
932327952Sdim
933327952Sdim  return RecoveryPath();
934327952Sdim}
935327952Sdim
936327952Sdim/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
937327952Sdim/// will be printed before the first one is logged. A newline will be printed
938327952Sdim/// after each error.
939327952Sdim///
940327952Sdim/// This is useful in the base level of your program to allow clean termination
941327952Sdim/// (allowing clean deallocation of resources, etc.), while reporting error
942327952Sdim/// information to the user.
943327952Sdimvoid logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
944327952Sdim
945327952Sdim/// Write all error messages (if any) in E to a string. The newline character
946327952Sdim/// is used to separate error messages.
947327952Sdiminline std::string toString(Error E) {
948327952Sdim  SmallVector<std::string, 2> Errors;
949327952Sdim  handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
950327952Sdim    Errors.push_back(EI.message());
951327952Sdim  });
952327952Sdim  return join(Errors.begin(), Errors.end(), "\n");
953327952Sdim}
954327952Sdim
955327952Sdim/// Consume a Error without doing anything. This method should be used
956327952Sdim/// only where an error can be considered a reasonable and expected return
957327952Sdim/// value.
958327952Sdim///
959327952Sdim/// Uses of this method are potentially indicative of design problems: If it's
960327952Sdim/// legitimate to do nothing while processing an "error", the error-producer
961327952Sdim/// might be more clearly refactored to return an Optional<T>.
962327952Sdiminline void consumeError(Error Err) {
963327952Sdim  handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
964327952Sdim}
965327952Sdim
966327952Sdim/// Helper for Errors used as out-parameters.
967327952Sdim///
968327952Sdim/// This helper is for use with the Error-as-out-parameter idiom, where an error
969327952Sdim/// is passed to a function or method by reference, rather than being returned.
970327952Sdim/// In such cases it is helpful to set the checked bit on entry to the function
971327952Sdim/// so that the error can be written to (unchecked Errors abort on assignment)
972327952Sdim/// and clear the checked bit on exit so that clients cannot accidentally forget
973327952Sdim/// to check the result. This helper performs these actions automatically using
974327952Sdim/// RAII:
975327952Sdim///
976327952Sdim///   @code{.cpp}
977327952Sdim///   Result foo(Error &Err) {
978327952Sdim///     ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
979327952Sdim///     // <body of foo>
980327952Sdim///     // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
981327952Sdim///   }
982327952Sdim///   @endcode
983327952Sdim///
984327952Sdim/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
985327952Sdim/// used with optional Errors (Error pointers that are allowed to be null). If
986327952Sdim/// ErrorAsOutParameter took an Error reference, an instance would have to be
987327952Sdim/// created inside every condition that verified that Error was non-null. By
988327952Sdim/// taking an Error pointer we can just create one instance at the top of the
989327952Sdim/// function.
990327952Sdimclass ErrorAsOutParameter {
991327952Sdimpublic:
992327952Sdim  ErrorAsOutParameter(Error *Err) : Err(Err) {
993327952Sdim    // Raise the checked bit if Err is success.
994327952Sdim    if (Err)
995327952Sdim      (void)!!*Err;
996327952Sdim  }
997327952Sdim
998327952Sdim  ~ErrorAsOutParameter() {
999327952Sdim    // Clear the checked bit.
1000327952Sdim    if (Err && !*Err)
1001327952Sdim      *Err = Error::success();
1002327952Sdim  }
1003327952Sdim
1004327952Sdimprivate:
1005327952Sdim  Error *Err;
1006327952Sdim};
1007327952Sdim
1008321369Sdim/// Helper for Expected<T>s used as out-parameters.
1009321369Sdim///
1010321369Sdim/// See ErrorAsOutParameter.
1011321369Sdimtemplate <typename T>
1012321369Sdimclass ExpectedAsOutParameter {
1013321369Sdimpublic:
1014321369Sdim  ExpectedAsOutParameter(Expected<T> *ValOrErr)
1015321369Sdim    : ValOrErr(ValOrErr) {
1016321369Sdim    if (ValOrErr)
1017321369Sdim      (void)!!*ValOrErr;
1018321369Sdim  }
1019321369Sdim
1020321369Sdim  ~ExpectedAsOutParameter() {
1021321369Sdim    if (ValOrErr)
1022321369Sdim      ValOrErr->setUnchecked();
1023321369Sdim  }
1024321369Sdim
1025321369Sdimprivate:
1026321369Sdim  Expected<T> *ValOrErr;
1027321369Sdim};
1028321369Sdim
1029303231Sdim/// This class wraps a std::error_code in a Error.
1030303231Sdim///
1031303231Sdim/// This is useful if you're writing an interface that returns a Error
1032303231Sdim/// (or Expected) and you want to call code that still returns
1033303231Sdim/// std::error_codes.
1034303231Sdimclass ECError : public ErrorInfo<ECError> {
1035303231Sdim  friend Error errorCodeToError(std::error_code);
1036314564Sdim
1037303231Sdimpublic:
1038303231Sdim  void setErrorCode(std::error_code EC) { this->EC = EC; }
1039303231Sdim  std::error_code convertToErrorCode() const override { return EC; }
1040303231Sdim  void log(raw_ostream &OS) const override { OS << EC.message(); }
1041303231Sdim
1042303231Sdim  // Used by ErrorInfo::classID.
1043303231Sdim  static char ID;
1044303231Sdim
1045303231Sdimprotected:
1046303231Sdim  ECError() = default;
1047303231Sdim  ECError(std::error_code EC) : EC(EC) {}
1048314564Sdim
1049303231Sdim  std::error_code EC;
1050303231Sdim};
1051303231Sdim
1052303231Sdim/// The value returned by this function can be returned from convertToErrorCode
1053303231Sdim/// for Error values where no sensible translation to std::error_code exists.
1054303231Sdim/// It should only be used in this situation, and should never be used where a
1055303231Sdim/// sensible conversion to std::error_code is available, as attempts to convert
1056303231Sdim/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1057303231Sdim///error to try to convert such a value).
1058303231Sdimstd::error_code inconvertibleErrorCode();
1059303231Sdim
1060303231Sdim/// Helper for converting an std::error_code to a Error.
1061303231SdimError errorCodeToError(std::error_code EC);
1062303231Sdim
1063303231Sdim/// Helper for converting an ECError to a std::error_code.
1064303231Sdim///
1065303231Sdim/// This method requires that Err be Error() or an ECError, otherwise it
1066303231Sdim/// will trigger a call to abort().
1067303231Sdimstd::error_code errorToErrorCode(Error Err);
1068303231Sdim
1069303231Sdim/// Convert an ErrorOr<T> to an Expected<T>.
1070303231Sdimtemplate <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1071303231Sdim  if (auto EC = EO.getError())
1072303231Sdim    return errorCodeToError(EC);
1073303231Sdim  return std::move(*EO);
1074303231Sdim}
1075303231Sdim
1076303231Sdim/// Convert an Expected<T> to an ErrorOr<T>.
1077303231Sdimtemplate <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1078303231Sdim  if (auto Err = E.takeError())
1079303231Sdim    return errorToErrorCode(std::move(Err));
1080303231Sdim  return std::move(*E);
1081303231Sdim}
1082303231Sdim
1083303231Sdim/// This class wraps a string in an Error.
1084303231Sdim///
1085303231Sdim/// StringError is useful in cases where the client is not expected to be able
1086303231Sdim/// to consume the specific error message programmatically (for example, if the
1087303231Sdim/// error message is to be presented to the user).
1088303231Sdimclass StringError : public ErrorInfo<StringError> {
1089303231Sdimpublic:
1090303231Sdim  static char ID;
1091314564Sdim
1092303231Sdim  StringError(const Twine &S, std::error_code EC);
1093314564Sdim
1094303231Sdim  void log(raw_ostream &OS) const override;
1095303231Sdim  std::error_code convertToErrorCode() const override;
1096314564Sdim
1097321369Sdim  const std::string &getMessage() const { return Msg; }
1098321369Sdim
1099303231Sdimprivate:
1100303231Sdim  std::string Msg;
1101303231Sdim  std::error_code EC;
1102303231Sdim};
1103303231Sdim
1104303231Sdim/// Helper for check-and-exit error handling.
1105303231Sdim///
1106303231Sdim/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1107303231Sdim///
1108303231Sdimclass ExitOnError {
1109303231Sdimpublic:
1110303231Sdim  /// Create an error on exit helper.
1111303231Sdim  ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1112303231Sdim      : Banner(std::move(Banner)),
1113303231Sdim        GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1114303231Sdim
1115303231Sdim  /// Set the banner string for any errors caught by operator().
1116303231Sdim  void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1117303231Sdim
1118303231Sdim  /// Set the exit-code mapper function.
1119303231Sdim  void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1120303231Sdim    this->GetExitCode = std::move(GetExitCode);
1121303231Sdim  }
1122303231Sdim
1123303231Sdim  /// Check Err. If it's in a failure state log the error(s) and exit.
1124303231Sdim  void operator()(Error Err) const { checkError(std::move(Err)); }
1125303231Sdim
1126303231Sdim  /// Check E. If it's in a success state then return the contained value. If
1127303231Sdim  /// it's in a failure state log the error(s) and exit.
1128303231Sdim  template <typename T> T operator()(Expected<T> &&E) const {
1129303231Sdim    checkError(E.takeError());
1130303231Sdim    return std::move(*E);
1131303231Sdim  }
1132303231Sdim
1133303231Sdim  /// Check E. If it's in a success state then return the contained reference. If
1134303231Sdim  /// it's in a failure state log the error(s) and exit.
1135303231Sdim  template <typename T> T& operator()(Expected<T&> &&E) const {
1136303231Sdim    checkError(E.takeError());
1137303231Sdim    return *E;
1138303231Sdim  }
1139303231Sdim
1140303231Sdimprivate:
1141303231Sdim  void checkError(Error Err) const {
1142303231Sdim    if (Err) {
1143303231Sdim      int ExitCode = GetExitCode(Err);
1144303231Sdim      logAllUnhandledErrors(std::move(Err), errs(), Banner);
1145303231Sdim      exit(ExitCode);
1146303231Sdim    }
1147303231Sdim  }
1148303231Sdim
1149303231Sdim  std::string Banner;
1150303231Sdim  std::function<int(const Error &)> GetExitCode;
1151303231Sdim};
1152303231Sdim
1153314564Sdim} // end namespace llvm
1154303231Sdim
1155303231Sdim#endif // LLVM_SUPPORT_ERROR_H
1156