Error.h revision 341825
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"
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 {
158303231Sdim  // ErrorList needs to be able to yank ErrorInfoBase pointers out of this
159303231Sdim  // class to add to the error list.
160303231Sdim  friend class ErrorList;
161303231Sdim
162303231Sdim  // handleErrors needs to be able to set the Checked flag.
163303231Sdim  template <typename... HandlerTs>
164303231Sdim  friend Error handleErrors(Error E, HandlerTs &&... Handlers);
165303231Sdim
166303231Sdim  // Expected<T> needs to be able to steal the payload when constructed from an
167303231Sdim  // error.
168314564Sdim  template <typename T> friend class Expected;
169303231Sdim
170314564Sdimprotected:
171303231Sdim  /// Create a success value. Prefer using 'Error::success()' for readability
172321369Sdim  Error() {
173303231Sdim    setPtr(nullptr);
174303231Sdim    setChecked(false);
175303231Sdim  }
176303231Sdim
177314564Sdimpublic:
178314564Sdim  /// Create a success value.
179314564Sdim  static ErrorSuccess success();
180303231Sdim
181303231Sdim  // Errors are not copy-constructable.
182303231Sdim  Error(const Error &Other) = delete;
183303231Sdim
184303231Sdim  /// Move-construct an error value. The newly constructed error is considered
185303231Sdim  /// unchecked, even if the source error had been checked. The original error
186303231Sdim  /// becomes a checked Success value, regardless of its original state.
187321369Sdim  Error(Error &&Other) {
188303231Sdim    setChecked(true);
189303231Sdim    *this = std::move(Other);
190303231Sdim  }
191303231Sdim
192303231Sdim  /// Create an error value. Prefer using the 'make_error' function, but
193303231Sdim  /// this constructor can be useful when "re-throwing" errors from handlers.
194303231Sdim  Error(std::unique_ptr<ErrorInfoBase> Payload) {
195303231Sdim    setPtr(Payload.release());
196303231Sdim    setChecked(false);
197303231Sdim  }
198303231Sdim
199303231Sdim  // Errors are not copy-assignable.
200303231Sdim  Error &operator=(const Error &Other) = delete;
201303231Sdim
202303231Sdim  /// Move-assign an error value. The current error must represent success, you
203303231Sdim  /// you cannot overwrite an unhandled error. The current error is then
204303231Sdim  /// considered unchecked. The source error becomes a checked success value,
205303231Sdim  /// regardless of its original state.
206303231Sdim  Error &operator=(Error &&Other) {
207303231Sdim    // Don't allow overwriting of unchecked values.
208303231Sdim    assertIsChecked();
209303231Sdim    setPtr(Other.getPtr());
210303231Sdim
211303231Sdim    // This Error is unchecked, even if the source error was checked.
212303231Sdim    setChecked(false);
213303231Sdim
214303231Sdim    // Null out Other's payload and set its checked bit.
215303231Sdim    Other.setPtr(nullptr);
216303231Sdim    Other.setChecked(true);
217303231Sdim
218303231Sdim    return *this;
219303231Sdim  }
220303231Sdim
221303231Sdim  /// Destroy a Error. Fails with a call to abort() if the error is
222303231Sdim  /// unchecked.
223303231Sdim  ~Error() {
224303231Sdim    assertIsChecked();
225303231Sdim    delete getPtr();
226303231Sdim  }
227303231Sdim
228303231Sdim  /// Bool conversion. Returns true if this Error is in a failure state,
229303231Sdim  /// and false if it is in an accept state. If the error is in a Success state
230303231Sdim  /// it will be considered checked.
231303231Sdim  explicit operator bool() {
232303231Sdim    setChecked(getPtr() == nullptr);
233303231Sdim    return getPtr() != nullptr;
234303231Sdim  }
235303231Sdim
236303231Sdim  /// Check whether one error is a subclass of another.
237303231Sdim  template <typename ErrT> bool isA() const {
238303231Sdim    return getPtr() && getPtr()->isA(ErrT::classID());
239303231Sdim  }
240303231Sdim
241321369Sdim  /// Returns the dynamic class id of this error, or null if this is a success
242321369Sdim  /// value.
243321369Sdim  const void* dynamicClassID() const {
244321369Sdim    if (!getPtr())
245321369Sdim      return nullptr;
246321369Sdim    return getPtr()->dynamicClassID();
247321369Sdim  }
248321369Sdim
249303231Sdimprivate:
250327952Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
251327952Sdim  // assertIsChecked() happens very frequently, but under normal circumstances
252327952Sdim  // is supposed to be a no-op.  So we want it to be inlined, but having a bunch
253327952Sdim  // of debug prints can cause the function to be too large for inlining.  So
254327952Sdim  // it's important that we define this function out of line so that it can't be
255327952Sdim  // inlined.
256327952Sdim  LLVM_ATTRIBUTE_NORETURN
257327952Sdim  void fatalUncheckedError() const;
258327952Sdim#endif
259327952Sdim
260303231Sdim  void assertIsChecked() {
261314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
262327952Sdim    if (LLVM_UNLIKELY(!getChecked() || getPtr()))
263327952Sdim      fatalUncheckedError();
264303231Sdim#endif
265303231Sdim  }
266303231Sdim
267303231Sdim  ErrorInfoBase *getPtr() const {
268314564Sdim    return reinterpret_cast<ErrorInfoBase*>(
269314564Sdim             reinterpret_cast<uintptr_t>(Payload) &
270314564Sdim             ~static_cast<uintptr_t>(0x1));
271303231Sdim  }
272303231Sdim
273303231Sdim  void setPtr(ErrorInfoBase *EI) {
274314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
275314564Sdim    Payload = reinterpret_cast<ErrorInfoBase*>(
276314564Sdim                (reinterpret_cast<uintptr_t>(EI) &
277314564Sdim                 ~static_cast<uintptr_t>(0x1)) |
278314564Sdim                (reinterpret_cast<uintptr_t>(Payload) & 0x1));
279303231Sdim#else
280303231Sdim    Payload = EI;
281303231Sdim#endif
282303231Sdim  }
283303231Sdim
284303231Sdim  bool getChecked() const {
285314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
286314564Sdim    return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
287303231Sdim#else
288303231Sdim    return true;
289303231Sdim#endif
290303231Sdim  }
291303231Sdim
292303231Sdim  void setChecked(bool V) {
293314564Sdim    Payload = reinterpret_cast<ErrorInfoBase*>(
294314564Sdim                (reinterpret_cast<uintptr_t>(Payload) &
295314564Sdim                  ~static_cast<uintptr_t>(0x1)) |
296314564Sdim                  (V ? 0 : 1));
297303231Sdim  }
298303231Sdim
299303231Sdim  std::unique_ptr<ErrorInfoBase> takePayload() {
300303231Sdim    std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
301303231Sdim    setPtr(nullptr);
302303231Sdim    setChecked(true);
303303231Sdim    return Tmp;
304303231Sdim  }
305303231Sdim
306341825Sdim  friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
307341825Sdim    if (auto P = E.getPtr())
308341825Sdim      P->log(OS);
309341825Sdim    else
310341825Sdim      OS << "success";
311341825Sdim    return OS;
312341825Sdim  }
313341825Sdim
314321369Sdim  ErrorInfoBase *Payload = nullptr;
315303231Sdim};
316303231Sdim
317314564Sdim/// Subclass of Error for the sole purpose of identifying the success path in
318314564Sdim/// the type system. This allows to catch invalid conversion to Expected<T> at
319314564Sdim/// compile time.
320314564Sdimclass ErrorSuccess : public Error {};
321314564Sdim
322314564Sdiminline ErrorSuccess Error::success() { return ErrorSuccess(); }
323314564Sdim
324303231Sdim/// Make a Error instance representing failure using the given error info
325303231Sdim/// type.
326303231Sdimtemplate <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
327303231Sdim  return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
328303231Sdim}
329303231Sdim
330303231Sdim/// Base class for user error types. Users should declare their error types
331303231Sdim/// like:
332303231Sdim///
333303231Sdim/// class MyError : public ErrorInfo<MyError> {
334303231Sdim///   ....
335303231Sdim/// };
336303231Sdim///
337303231Sdim/// This class provides an implementation of the ErrorInfoBase::kind
338303231Sdim/// method, which is used by the Error RTTI system.
339303231Sdimtemplate <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
340303231Sdimclass ErrorInfo : public ParentErrT {
341303231Sdimpublic:
342321369Sdim  static const void *classID() { return &ThisErrT::ID; }
343321369Sdim
344321369Sdim  const void *dynamicClassID() const override { return &ThisErrT::ID; }
345321369Sdim
346303231Sdim  bool isA(const void *const ClassID) const override {
347303231Sdim    return ClassID == classID() || ParentErrT::isA(ClassID);
348303231Sdim  }
349303231Sdim};
350303231Sdim
351303231Sdim/// Special ErrorInfo subclass representing a list of ErrorInfos.
352303231Sdim/// Instances of this class are constructed by joinError.
353303231Sdimclass ErrorList final : public ErrorInfo<ErrorList> {
354303231Sdim  // handleErrors needs to be able to iterate the payload list of an
355303231Sdim  // ErrorList.
356303231Sdim  template <typename... HandlerTs>
357303231Sdim  friend Error handleErrors(Error E, HandlerTs &&... Handlers);
358303231Sdim
359303231Sdim  // joinErrors is implemented in terms of join.
360303231Sdim  friend Error joinErrors(Error, Error);
361303231Sdim
362303231Sdimpublic:
363303231Sdim  void log(raw_ostream &OS) const override {
364303231Sdim    OS << "Multiple errors:\n";
365303231Sdim    for (auto &ErrPayload : Payloads) {
366303231Sdim      ErrPayload->log(OS);
367303231Sdim      OS << "\n";
368303231Sdim    }
369303231Sdim  }
370303231Sdim
371303231Sdim  std::error_code convertToErrorCode() const override;
372303231Sdim
373303231Sdim  // Used by ErrorInfo::classID.
374303231Sdim  static char ID;
375303231Sdim
376303231Sdimprivate:
377303231Sdim  ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
378303231Sdim            std::unique_ptr<ErrorInfoBase> Payload2) {
379303231Sdim    assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
380303231Sdim           "ErrorList constructor payloads should be singleton errors");
381303231Sdim    Payloads.push_back(std::move(Payload1));
382303231Sdim    Payloads.push_back(std::move(Payload2));
383303231Sdim  }
384303231Sdim
385303231Sdim  static Error join(Error E1, Error E2) {
386303231Sdim    if (!E1)
387303231Sdim      return E2;
388303231Sdim    if (!E2)
389303231Sdim      return E1;
390303231Sdim    if (E1.isA<ErrorList>()) {
391303231Sdim      auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
392303231Sdim      if (E2.isA<ErrorList>()) {
393303231Sdim        auto E2Payload = E2.takePayload();
394303231Sdim        auto &E2List = static_cast<ErrorList &>(*E2Payload);
395303231Sdim        for (auto &Payload : E2List.Payloads)
396303231Sdim          E1List.Payloads.push_back(std::move(Payload));
397303231Sdim      } else
398303231Sdim        E1List.Payloads.push_back(E2.takePayload());
399303231Sdim
400303231Sdim      return E1;
401303231Sdim    }
402303231Sdim    if (E2.isA<ErrorList>()) {
403303231Sdim      auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
404303231Sdim      E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
405303231Sdim      return E2;
406303231Sdim    }
407303231Sdim    return Error(std::unique_ptr<ErrorList>(
408303231Sdim        new ErrorList(E1.takePayload(), E2.takePayload())));
409303231Sdim  }
410303231Sdim
411303231Sdim  std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
412303231Sdim};
413303231Sdim
414303231Sdim/// Concatenate errors. The resulting Error is unchecked, and contains the
415303231Sdim/// ErrorInfo(s), if any, contained in E1, followed by the
416303231Sdim/// ErrorInfo(s), if any, contained in E2.
417303231Sdiminline Error joinErrors(Error E1, Error E2) {
418303231Sdim  return ErrorList::join(std::move(E1), std::move(E2));
419303231Sdim}
420303231Sdim
421303231Sdim/// Tagged union holding either a T or a Error.
422303231Sdim///
423303231Sdim/// This class parallels ErrorOr, but replaces error_code with Error. Since
424303231Sdim/// Error cannot be copied, this class replaces getError() with
425303231Sdim/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
426303231Sdim/// error class type.
427314564Sdimtemplate <class T> class LLVM_NODISCARD Expected {
428321369Sdim  template <class T1> friend class ExpectedAsOutParameter;
429303231Sdim  template <class OtherT> friend class Expected;
430321369Sdim
431303231Sdim  static const bool isRef = std::is_reference<T>::value;
432303231Sdim
433341825Sdim  using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
434303231Sdim
435321369Sdim  using error_type = std::unique_ptr<ErrorInfoBase>;
436321369Sdim
437303231Sdimpublic:
438321369Sdim  using storage_type = typename std::conditional<isRef, wrap, T>::type;
439321369Sdim  using value_type = T;
440303231Sdim
441303231Sdimprivate:
442321369Sdim  using reference = typename std::remove_reference<T>::type &;
443321369Sdim  using const_reference = const typename std::remove_reference<T>::type &;
444321369Sdim  using pointer = typename std::remove_reference<T>::type *;
445321369Sdim  using const_pointer = const typename std::remove_reference<T>::type *;
446303231Sdim
447303231Sdimpublic:
448303231Sdim  /// Create an Expected<T> error value from the given Error.
449303231Sdim  Expected(Error Err)
450303231Sdim      : HasError(true)
451314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
452314564Sdim        // Expected is unchecked upon construction in Debug builds.
453314564Sdim        , Unchecked(true)
454303231Sdim#endif
455303231Sdim  {
456303231Sdim    assert(Err && "Cannot create Expected<T> from Error success value.");
457314564Sdim    new (getErrorStorage()) error_type(Err.takePayload());
458303231Sdim  }
459303231Sdim
460314564Sdim  /// Forbid to convert from Error::success() implicitly, this avoids having
461314564Sdim  /// Expected<T> foo() { return Error::success(); } which compiles otherwise
462314564Sdim  /// but triggers the assertion above.
463314564Sdim  Expected(ErrorSuccess) = delete;
464314564Sdim
465303231Sdim  /// Create an Expected<T> success value from the given OtherT value, which
466303231Sdim  /// must be convertible to T.
467303231Sdim  template <typename OtherT>
468303231Sdim  Expected(OtherT &&Val,
469303231Sdim           typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
470303231Sdim               * = nullptr)
471303231Sdim      : HasError(false)
472314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
473314564Sdim        // Expected is unchecked upon construction in Debug builds.
474314564Sdim        , Unchecked(true)
475303231Sdim#endif
476303231Sdim  {
477303231Sdim    new (getStorage()) storage_type(std::forward<OtherT>(Val));
478303231Sdim  }
479303231Sdim
480303231Sdim  /// Move construct an Expected<T> value.
481303231Sdim  Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
482303231Sdim
483303231Sdim  /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
484303231Sdim  /// must be convertible to T.
485303231Sdim  template <class OtherT>
486303231Sdim  Expected(Expected<OtherT> &&Other,
487303231Sdim           typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
488303231Sdim               * = nullptr) {
489303231Sdim    moveConstruct(std::move(Other));
490303231Sdim  }
491303231Sdim
492303231Sdim  /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
493303231Sdim  /// isn't convertible to T.
494303231Sdim  template <class OtherT>
495303231Sdim  explicit Expected(
496303231Sdim      Expected<OtherT> &&Other,
497303231Sdim      typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
498303231Sdim          nullptr) {
499303231Sdim    moveConstruct(std::move(Other));
500303231Sdim  }
501303231Sdim
502303231Sdim  /// Move-assign from another Expected<T>.
503303231Sdim  Expected &operator=(Expected &&Other) {
504303231Sdim    moveAssign(std::move(Other));
505303231Sdim    return *this;
506303231Sdim  }
507303231Sdim
508303231Sdim  /// Destroy an Expected<T>.
509303231Sdim  ~Expected() {
510303231Sdim    assertIsChecked();
511303231Sdim    if (!HasError)
512303231Sdim      getStorage()->~storage_type();
513303231Sdim    else
514303231Sdim      getErrorStorage()->~error_type();
515303231Sdim  }
516303231Sdim
517341825Sdim  /// Return false if there is an error.
518303231Sdim  explicit operator bool() {
519314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
520314564Sdim    Unchecked = HasError;
521303231Sdim#endif
522303231Sdim    return !HasError;
523303231Sdim  }
524303231Sdim
525341825Sdim  /// Returns a reference to the stored T value.
526303231Sdim  reference get() {
527303231Sdim    assertIsChecked();
528303231Sdim    return *getStorage();
529303231Sdim  }
530303231Sdim
531341825Sdim  /// Returns a const reference to the stored T value.
532303231Sdim  const_reference get() const {
533303231Sdim    assertIsChecked();
534303231Sdim    return const_cast<Expected<T> *>(this)->get();
535303231Sdim  }
536303231Sdim
537341825Sdim  /// Check that this Expected<T> is an error of type ErrT.
538303231Sdim  template <typename ErrT> bool errorIsA() const {
539321369Sdim    return HasError && (*getErrorStorage())->template isA<ErrT>();
540303231Sdim  }
541303231Sdim
542341825Sdim  /// Take ownership of the stored error.
543303231Sdim  /// After calling this the Expected<T> is in an indeterminate state that can
544303231Sdim  /// only be safely destructed. No further calls (beside the destructor) should
545303231Sdim  /// be made on the Expected<T> vaule.
546303231Sdim  Error takeError() {
547314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
548314564Sdim    Unchecked = false;
549303231Sdim#endif
550303231Sdim    return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
551303231Sdim  }
552303231Sdim
553341825Sdim  /// Returns a pointer to the stored T value.
554303231Sdim  pointer operator->() {
555303231Sdim    assertIsChecked();
556303231Sdim    return toPointer(getStorage());
557303231Sdim  }
558303231Sdim
559341825Sdim  /// Returns a const pointer to the stored T value.
560303231Sdim  const_pointer operator->() const {
561303231Sdim    assertIsChecked();
562303231Sdim    return toPointer(getStorage());
563303231Sdim  }
564303231Sdim
565341825Sdim  /// Returns a reference to the stored T value.
566303231Sdim  reference operator*() {
567303231Sdim    assertIsChecked();
568303231Sdim    return *getStorage();
569303231Sdim  }
570303231Sdim
571341825Sdim  /// Returns a const reference to the stored T value.
572303231Sdim  const_reference operator*() const {
573303231Sdim    assertIsChecked();
574303231Sdim    return *getStorage();
575303231Sdim  }
576303231Sdim
577303231Sdimprivate:
578303231Sdim  template <class T1>
579303231Sdim  static bool compareThisIfSameType(const T1 &a, const T1 &b) {
580303231Sdim    return &a == &b;
581303231Sdim  }
582303231Sdim
583303231Sdim  template <class T1, class T2>
584303231Sdim  static bool compareThisIfSameType(const T1 &a, const T2 &b) {
585303231Sdim    return false;
586303231Sdim  }
587303231Sdim
588303231Sdim  template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
589303231Sdim    HasError = Other.HasError;
590314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
591314564Sdim    Unchecked = true;
592314564Sdim    Other.Unchecked = false;
593303231Sdim#endif
594303231Sdim
595303231Sdim    if (!HasError)
596303231Sdim      new (getStorage()) storage_type(std::move(*Other.getStorage()));
597303231Sdim    else
598303231Sdim      new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
599303231Sdim  }
600303231Sdim
601303231Sdim  template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
602303231Sdim    assertIsChecked();
603303231Sdim
604303231Sdim    if (compareThisIfSameType(*this, Other))
605303231Sdim      return;
606303231Sdim
607303231Sdim    this->~Expected();
608303231Sdim    new (this) Expected(std::move(Other));
609303231Sdim  }
610303231Sdim
611303231Sdim  pointer toPointer(pointer Val) { return Val; }
612303231Sdim
613303231Sdim  const_pointer toPointer(const_pointer Val) const { return Val; }
614303231Sdim
615303231Sdim  pointer toPointer(wrap *Val) { return &Val->get(); }
616303231Sdim
617303231Sdim  const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
618303231Sdim
619303231Sdim  storage_type *getStorage() {
620303231Sdim    assert(!HasError && "Cannot get value when an error exists!");
621303231Sdim    return reinterpret_cast<storage_type *>(TStorage.buffer);
622303231Sdim  }
623303231Sdim
624303231Sdim  const storage_type *getStorage() const {
625303231Sdim    assert(!HasError && "Cannot get value when an error exists!");
626303231Sdim    return reinterpret_cast<const storage_type *>(TStorage.buffer);
627303231Sdim  }
628303231Sdim
629303231Sdim  error_type *getErrorStorage() {
630303231Sdim    assert(HasError && "Cannot get error when a value exists!");
631303231Sdim    return reinterpret_cast<error_type *>(ErrorStorage.buffer);
632303231Sdim  }
633303231Sdim
634321369Sdim  const error_type *getErrorStorage() const {
635321369Sdim    assert(HasError && "Cannot get error when a value exists!");
636321369Sdim    return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
637321369Sdim  }
638321369Sdim
639321369Sdim  // Used by ExpectedAsOutParameter to reset the checked flag.
640321369Sdim  void setUnchecked() {
641321369Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
642321369Sdim    Unchecked = true;
643321369Sdim#endif
644321369Sdim  }
645321369Sdim
646327952Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
647327952Sdim  LLVM_ATTRIBUTE_NORETURN
648327952Sdim  LLVM_ATTRIBUTE_NOINLINE
649327952Sdim  void fatalUncheckedExpected() const {
650327952Sdim    dbgs() << "Expected<T> must be checked before access or destruction.\n";
651327952Sdim    if (HasError) {
652327952Sdim      dbgs() << "Unchecked Expected<T> contained error:\n";
653327952Sdim      (*getErrorStorage())->log(dbgs());
654327952Sdim    } else
655327952Sdim      dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
656327952Sdim                "values in success mode must still be checked prior to being "
657327952Sdim                "destroyed).\n";
658327952Sdim    abort();
659327952Sdim  }
660327952Sdim#endif
661327952Sdim
662303231Sdim  void assertIsChecked() {
663314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
664327952Sdim    if (LLVM_UNLIKELY(Unchecked))
665327952Sdim      fatalUncheckedExpected();
666303231Sdim#endif
667303231Sdim  }
668303231Sdim
669303231Sdim  union {
670303231Sdim    AlignedCharArrayUnion<storage_type> TStorage;
671303231Sdim    AlignedCharArrayUnion<error_type> ErrorStorage;
672303231Sdim  };
673303231Sdim  bool HasError : 1;
674314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
675314564Sdim  bool Unchecked : 1;
676303231Sdim#endif
677303231Sdim};
678303231Sdim
679327952Sdim/// Report a serious error, calling any installed error handler. See
680327952Sdim/// ErrorHandling.h.
681327952SdimLLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err,
682327952Sdim                                                bool gen_crash_diag = true);
683327952Sdim
684327952Sdim/// Report a fatal error if Err is a failure value.
685327952Sdim///
686327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it
687327952Sdim/// is known that the Error will always be a success value. E.g.
688327952Sdim///
689327952Sdim///   @code{.cpp}
690327952Sdim///   // foo only attempts the fallible operation if DoFallibleOperation is
691327952Sdim///   // true. If DoFallibleOperation is false then foo always returns
692327952Sdim///   // Error::success().
693327952Sdim///   Error foo(bool DoFallibleOperation);
694327952Sdim///
695327952Sdim///   cantFail(foo(false));
696327952Sdim///   @endcode
697327952Sdiminline void cantFail(Error Err, const char *Msg = nullptr) {
698327952Sdim  if (Err) {
699327952Sdim    if (!Msg)
700327952Sdim      Msg = "Failure value returned from cantFail wrapped call";
701327952Sdim    llvm_unreachable(Msg);
702327952Sdim  }
703327952Sdim}
704327952Sdim
705327952Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
706327952Sdim/// returns the contained value.
707327952Sdim///
708327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it
709327952Sdim/// is known that the Error will always be a success value. E.g.
710327952Sdim///
711327952Sdim///   @code{.cpp}
712327952Sdim///   // foo only attempts the fallible operation if DoFallibleOperation is
713327952Sdim///   // true. If DoFallibleOperation is false then foo always returns an int.
714327952Sdim///   Expected<int> foo(bool DoFallibleOperation);
715327952Sdim///
716327952Sdim///   int X = cantFail(foo(false));
717327952Sdim///   @endcode
718327952Sdimtemplate <typename T>
719327952SdimT cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
720327952Sdim  if (ValOrErr)
721327952Sdim    return std::move(*ValOrErr);
722327952Sdim  else {
723327952Sdim    if (!Msg)
724327952Sdim      Msg = "Failure value returned from cantFail wrapped call";
725327952Sdim    llvm_unreachable(Msg);
726327952Sdim  }
727327952Sdim}
728327952Sdim
729327952Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
730327952Sdim/// returns the contained reference.
731327952Sdim///
732327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it
733327952Sdim/// is known that the Error will always be a success value. E.g.
734327952Sdim///
735327952Sdim///   @code{.cpp}
736327952Sdim///   // foo only attempts the fallible operation if DoFallibleOperation is
737327952Sdim///   // true. If DoFallibleOperation is false then foo always returns a Bar&.
738327952Sdim///   Expected<Bar&> foo(bool DoFallibleOperation);
739327952Sdim///
740327952Sdim///   Bar &X = cantFail(foo(false));
741327952Sdim///   @endcode
742327952Sdimtemplate <typename T>
743327952SdimT& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
744327952Sdim  if (ValOrErr)
745327952Sdim    return *ValOrErr;
746327952Sdim  else {
747327952Sdim    if (!Msg)
748327952Sdim      Msg = "Failure value returned from cantFail wrapped call";
749327952Sdim    llvm_unreachable(Msg);
750327952Sdim  }
751327952Sdim}
752327952Sdim
753327952Sdim/// Helper for testing applicability of, and applying, handlers for
754327952Sdim/// ErrorInfo types.
755327952Sdimtemplate <typename HandlerT>
756327952Sdimclass ErrorHandlerTraits
757327952Sdim    : public ErrorHandlerTraits<decltype(
758327952Sdim          &std::remove_reference<HandlerT>::type::operator())> {};
759327952Sdim
760327952Sdim// Specialization functions of the form 'Error (const ErrT&)'.
761327952Sdimtemplate <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
762327952Sdimpublic:
763327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
764327952Sdim    return E.template isA<ErrT>();
765327952Sdim  }
766327952Sdim
767327952Sdim  template <typename HandlerT>
768327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
769327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
770327952Sdim    return H(static_cast<ErrT &>(*E));
771327952Sdim  }
772327952Sdim};
773327952Sdim
774327952Sdim// Specialization functions of the form 'void (const ErrT&)'.
775327952Sdimtemplate <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
776327952Sdimpublic:
777327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
778327952Sdim    return E.template isA<ErrT>();
779327952Sdim  }
780327952Sdim
781327952Sdim  template <typename HandlerT>
782327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
783327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
784327952Sdim    H(static_cast<ErrT &>(*E));
785327952Sdim    return Error::success();
786327952Sdim  }
787327952Sdim};
788327952Sdim
789327952Sdim/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
790327952Sdimtemplate <typename ErrT>
791327952Sdimclass ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
792327952Sdimpublic:
793327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
794327952Sdim    return E.template isA<ErrT>();
795327952Sdim  }
796327952Sdim
797327952Sdim  template <typename HandlerT>
798327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
799327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
800327952Sdim    std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
801327952Sdim    return H(std::move(SubE));
802327952Sdim  }
803327952Sdim};
804327952Sdim
805327952Sdim/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
806327952Sdimtemplate <typename ErrT>
807327952Sdimclass ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
808327952Sdimpublic:
809327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
810327952Sdim    return E.template isA<ErrT>();
811327952Sdim  }
812327952Sdim
813327952Sdim  template <typename HandlerT>
814327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
815327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
816327952Sdim    std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
817327952Sdim    H(std::move(SubE));
818327952Sdim    return Error::success();
819327952Sdim  }
820327952Sdim};
821327952Sdim
822327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'.
823327952Sdimtemplate <typename C, typename RetT, typename ErrT>
824327952Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &)>
825327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
826327952Sdim
827327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'.
828327952Sdimtemplate <typename C, typename RetT, typename ErrT>
829327952Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
830327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
831327952Sdim
832327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'.
833327952Sdimtemplate <typename C, typename RetT, typename ErrT>
834327952Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
835327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
836327952Sdim
837327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'.
838327952Sdimtemplate <typename C, typename RetT, typename ErrT>
839327952Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
840327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
841327952Sdim
842327952Sdim/// Specialization for member functions of the form
843327952Sdim/// 'RetT (std::unique_ptr<ErrT>)'.
844327952Sdimtemplate <typename C, typename RetT, typename ErrT>
845327952Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
846327952Sdim    : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
847327952Sdim
848327952Sdim/// Specialization for member functions of the form
849327952Sdim/// 'RetT (std::unique_ptr<ErrT>) const'.
850327952Sdimtemplate <typename C, typename RetT, typename ErrT>
851327952Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
852327952Sdim    : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
853327952Sdim
854327952Sdiminline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
855327952Sdim  return Error(std::move(Payload));
856327952Sdim}
857327952Sdim
858327952Sdimtemplate <typename HandlerT, typename... HandlerTs>
859327952SdimError handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
860327952Sdim                      HandlerT &&Handler, HandlerTs &&... Handlers) {
861327952Sdim  if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
862327952Sdim    return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
863327952Sdim                                               std::move(Payload));
864327952Sdim  return handleErrorImpl(std::move(Payload),
865327952Sdim                         std::forward<HandlerTs>(Handlers)...);
866327952Sdim}
867327952Sdim
868327952Sdim/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
869327952Sdim/// unhandled errors (or Errors returned by handlers) are re-concatenated and
870327952Sdim/// returned.
871327952Sdim/// Because this function returns an error, its result must also be checked
872327952Sdim/// or returned. If you intend to handle all errors use handleAllErrors
873327952Sdim/// (which returns void, and will abort() on unhandled errors) instead.
874327952Sdimtemplate <typename... HandlerTs>
875327952SdimError handleErrors(Error E, HandlerTs &&... Hs) {
876327952Sdim  if (!E)
877327952Sdim    return Error::success();
878327952Sdim
879327952Sdim  std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
880327952Sdim
881327952Sdim  if (Payload->isA<ErrorList>()) {
882327952Sdim    ErrorList &List = static_cast<ErrorList &>(*Payload);
883327952Sdim    Error R;
884327952Sdim    for (auto &P : List.Payloads)
885327952Sdim      R = ErrorList::join(
886327952Sdim          std::move(R),
887327952Sdim          handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
888327952Sdim    return R;
889327952Sdim  }
890327952Sdim
891327952Sdim  return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
892327952Sdim}
893327952Sdim
894341825Sdim/// Behaves the same as handleErrors, except that by contract all errors
895341825Sdim/// *must* be handled by the given handlers (i.e. there must be no remaining
896341825Sdim/// errors after running the handlers, or llvm_unreachable is called).
897327952Sdimtemplate <typename... HandlerTs>
898327952Sdimvoid handleAllErrors(Error E, HandlerTs &&... Handlers) {
899327952Sdim  cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
900327952Sdim}
901327952Sdim
902327952Sdim/// Check that E is a non-error, then drop it.
903341825Sdim/// If E is an error, llvm_unreachable will be called.
904327952Sdiminline void handleAllErrors(Error E) {
905327952Sdim  cantFail(std::move(E));
906327952Sdim}
907327952Sdim
908327952Sdim/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
909327952Sdim///
910327952Sdim/// If the incoming value is a success value it is returned unmodified. If it
911327952Sdim/// is a failure value then it the contained error is passed to handleErrors.
912327952Sdim/// If handleErrors is able to handle the error then the RecoveryPath functor
913327952Sdim/// is called to supply the final result. If handleErrors is not able to
914327952Sdim/// handle all errors then the unhandled errors are returned.
915327952Sdim///
916327952Sdim/// This utility enables the follow pattern:
917327952Sdim///
918327952Sdim///   @code{.cpp}
919327952Sdim///   enum FooStrategy { Aggressive, Conservative };
920327952Sdim///   Expected<Foo> foo(FooStrategy S);
921327952Sdim///
922327952Sdim///   auto ResultOrErr =
923327952Sdim///     handleExpected(
924327952Sdim///       foo(Aggressive),
925327952Sdim///       []() { return foo(Conservative); },
926327952Sdim///       [](AggressiveStrategyError&) {
927327952Sdim///         // Implicitly conusme this - we'll recover by using a conservative
928327952Sdim///         // strategy.
929327952Sdim///       });
930327952Sdim///
931327952Sdim///   @endcode
932327952Sdimtemplate <typename T, typename RecoveryFtor, typename... HandlerTs>
933327952SdimExpected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
934327952Sdim                           HandlerTs &&... Handlers) {
935327952Sdim  if (ValOrErr)
936327952Sdim    return ValOrErr;
937327952Sdim
938327952Sdim  if (auto Err = handleErrors(ValOrErr.takeError(),
939327952Sdim                              std::forward<HandlerTs>(Handlers)...))
940327952Sdim    return std::move(Err);
941327952Sdim
942327952Sdim  return RecoveryPath();
943327952Sdim}
944327952Sdim
945327952Sdim/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
946327952Sdim/// will be printed before the first one is logged. A newline will be printed
947327952Sdim/// after each error.
948327952Sdim///
949327952Sdim/// This is useful in the base level of your program to allow clean termination
950327952Sdim/// (allowing clean deallocation of resources, etc.), while reporting error
951327952Sdim/// information to the user.
952327952Sdimvoid logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
953327952Sdim
954327952Sdim/// Write all error messages (if any) in E to a string. The newline character
955327952Sdim/// is used to separate error messages.
956327952Sdiminline std::string toString(Error E) {
957327952Sdim  SmallVector<std::string, 2> Errors;
958327952Sdim  handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
959327952Sdim    Errors.push_back(EI.message());
960327952Sdim  });
961327952Sdim  return join(Errors.begin(), Errors.end(), "\n");
962327952Sdim}
963327952Sdim
964327952Sdim/// Consume a Error without doing anything. This method should be used
965327952Sdim/// only where an error can be considered a reasonable and expected return
966327952Sdim/// value.
967327952Sdim///
968327952Sdim/// Uses of this method are potentially indicative of design problems: If it's
969327952Sdim/// legitimate to do nothing while processing an "error", the error-producer
970327952Sdim/// might be more clearly refactored to return an Optional<T>.
971327952Sdiminline void consumeError(Error Err) {
972327952Sdim  handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
973327952Sdim}
974327952Sdim
975341825Sdim/// Helper for converting an Error to a bool.
976341825Sdim///
977341825Sdim/// This method returns true if Err is in an error state, or false if it is
978341825Sdim/// in a success state.  Puts Err in a checked state in both cases (unlike
979341825Sdim/// Error::operator bool(), which only does this for success states).
980341825Sdiminline bool errorToBool(Error Err) {
981341825Sdim  bool IsError = static_cast<bool>(Err);
982341825Sdim  if (IsError)
983341825Sdim    consumeError(std::move(Err));
984341825Sdim  return IsError;
985341825Sdim}
986341825Sdim
987327952Sdim/// Helper for Errors used as out-parameters.
988327952Sdim///
989327952Sdim/// This helper is for use with the Error-as-out-parameter idiom, where an error
990327952Sdim/// is passed to a function or method by reference, rather than being returned.
991327952Sdim/// In such cases it is helpful to set the checked bit on entry to the function
992327952Sdim/// so that the error can be written to (unchecked Errors abort on assignment)
993327952Sdim/// and clear the checked bit on exit so that clients cannot accidentally forget
994327952Sdim/// to check the result. This helper performs these actions automatically using
995327952Sdim/// RAII:
996327952Sdim///
997327952Sdim///   @code{.cpp}
998327952Sdim///   Result foo(Error &Err) {
999327952Sdim///     ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1000327952Sdim///     // <body of foo>
1001327952Sdim///     // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1002327952Sdim///   }
1003327952Sdim///   @endcode
1004327952Sdim///
1005327952Sdim/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1006327952Sdim/// used with optional Errors (Error pointers that are allowed to be null). If
1007327952Sdim/// ErrorAsOutParameter took an Error reference, an instance would have to be
1008327952Sdim/// created inside every condition that verified that Error was non-null. By
1009327952Sdim/// taking an Error pointer we can just create one instance at the top of the
1010327952Sdim/// function.
1011327952Sdimclass ErrorAsOutParameter {
1012327952Sdimpublic:
1013327952Sdim  ErrorAsOutParameter(Error *Err) : Err(Err) {
1014327952Sdim    // Raise the checked bit if Err is success.
1015327952Sdim    if (Err)
1016327952Sdim      (void)!!*Err;
1017327952Sdim  }
1018327952Sdim
1019327952Sdim  ~ErrorAsOutParameter() {
1020327952Sdim    // Clear the checked bit.
1021327952Sdim    if (Err && !*Err)
1022327952Sdim      *Err = Error::success();
1023327952Sdim  }
1024327952Sdim
1025327952Sdimprivate:
1026327952Sdim  Error *Err;
1027327952Sdim};
1028327952Sdim
1029321369Sdim/// Helper for Expected<T>s used as out-parameters.
1030321369Sdim///
1031321369Sdim/// See ErrorAsOutParameter.
1032321369Sdimtemplate <typename T>
1033321369Sdimclass ExpectedAsOutParameter {
1034321369Sdimpublic:
1035321369Sdim  ExpectedAsOutParameter(Expected<T> *ValOrErr)
1036321369Sdim    : ValOrErr(ValOrErr) {
1037321369Sdim    if (ValOrErr)
1038321369Sdim      (void)!!*ValOrErr;
1039321369Sdim  }
1040321369Sdim
1041321369Sdim  ~ExpectedAsOutParameter() {
1042321369Sdim    if (ValOrErr)
1043321369Sdim      ValOrErr->setUnchecked();
1044321369Sdim  }
1045321369Sdim
1046321369Sdimprivate:
1047321369Sdim  Expected<T> *ValOrErr;
1048321369Sdim};
1049321369Sdim
1050303231Sdim/// This class wraps a std::error_code in a Error.
1051303231Sdim///
1052303231Sdim/// This is useful if you're writing an interface that returns a Error
1053303231Sdim/// (or Expected) and you want to call code that still returns
1054303231Sdim/// std::error_codes.
1055303231Sdimclass ECError : public ErrorInfo<ECError> {
1056303231Sdim  friend Error errorCodeToError(std::error_code);
1057314564Sdim
1058303231Sdimpublic:
1059303231Sdim  void setErrorCode(std::error_code EC) { this->EC = EC; }
1060303231Sdim  std::error_code convertToErrorCode() const override { return EC; }
1061303231Sdim  void log(raw_ostream &OS) const override { OS << EC.message(); }
1062303231Sdim
1063303231Sdim  // Used by ErrorInfo::classID.
1064303231Sdim  static char ID;
1065303231Sdim
1066303231Sdimprotected:
1067303231Sdim  ECError() = default;
1068303231Sdim  ECError(std::error_code EC) : EC(EC) {}
1069314564Sdim
1070303231Sdim  std::error_code EC;
1071303231Sdim};
1072303231Sdim
1073303231Sdim/// The value returned by this function can be returned from convertToErrorCode
1074303231Sdim/// for Error values where no sensible translation to std::error_code exists.
1075303231Sdim/// It should only be used in this situation, and should never be used where a
1076303231Sdim/// sensible conversion to std::error_code is available, as attempts to convert
1077303231Sdim/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1078303231Sdim///error to try to convert such a value).
1079303231Sdimstd::error_code inconvertibleErrorCode();
1080303231Sdim
1081303231Sdim/// Helper for converting an std::error_code to a Error.
1082303231SdimError errorCodeToError(std::error_code EC);
1083303231Sdim
1084303231Sdim/// Helper for converting an ECError to a std::error_code.
1085303231Sdim///
1086303231Sdim/// This method requires that Err be Error() or an ECError, otherwise it
1087303231Sdim/// will trigger a call to abort().
1088303231Sdimstd::error_code errorToErrorCode(Error Err);
1089303231Sdim
1090303231Sdim/// Convert an ErrorOr<T> to an Expected<T>.
1091303231Sdimtemplate <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1092303231Sdim  if (auto EC = EO.getError())
1093303231Sdim    return errorCodeToError(EC);
1094303231Sdim  return std::move(*EO);
1095303231Sdim}
1096303231Sdim
1097303231Sdim/// Convert an Expected<T> to an ErrorOr<T>.
1098303231Sdimtemplate <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1099303231Sdim  if (auto Err = E.takeError())
1100303231Sdim    return errorToErrorCode(std::move(Err));
1101303231Sdim  return std::move(*E);
1102303231Sdim}
1103303231Sdim
1104303231Sdim/// This class wraps a string in an Error.
1105303231Sdim///
1106303231Sdim/// StringError is useful in cases where the client is not expected to be able
1107303231Sdim/// to consume the specific error message programmatically (for example, if the
1108303231Sdim/// error message is to be presented to the user).
1109303231Sdimclass StringError : public ErrorInfo<StringError> {
1110303231Sdimpublic:
1111303231Sdim  static char ID;
1112314564Sdim
1113303231Sdim  StringError(const Twine &S, std::error_code EC);
1114314564Sdim
1115303231Sdim  void log(raw_ostream &OS) const override;
1116303231Sdim  std::error_code convertToErrorCode() const override;
1117314564Sdim
1118321369Sdim  const std::string &getMessage() const { return Msg; }
1119321369Sdim
1120303231Sdimprivate:
1121303231Sdim  std::string Msg;
1122303231Sdim  std::error_code EC;
1123303231Sdim};
1124303231Sdim
1125341825Sdim/// Create formatted StringError object.
1126341825Sdimtemplate <typename... Ts>
1127341825SdimError createStringError(std::error_code EC, char const *Fmt,
1128341825Sdim                        const Ts &... Vals) {
1129341825Sdim  std::string Buffer;
1130341825Sdim  raw_string_ostream Stream(Buffer);
1131341825Sdim  Stream << format(Fmt, Vals...);
1132341825Sdim  return make_error<StringError>(Stream.str(), EC);
1133341825Sdim}
1134341825Sdim
1135341825SdimError createStringError(std::error_code EC, char const *Msg);
1136341825Sdim
1137303231Sdim/// Helper for check-and-exit error handling.
1138303231Sdim///
1139303231Sdim/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1140303231Sdim///
1141303231Sdimclass ExitOnError {
1142303231Sdimpublic:
1143303231Sdim  /// Create an error on exit helper.
1144303231Sdim  ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1145303231Sdim      : Banner(std::move(Banner)),
1146303231Sdim        GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1147303231Sdim
1148303231Sdim  /// Set the banner string for any errors caught by operator().
1149303231Sdim  void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1150303231Sdim
1151303231Sdim  /// Set the exit-code mapper function.
1152303231Sdim  void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1153303231Sdim    this->GetExitCode = std::move(GetExitCode);
1154303231Sdim  }
1155303231Sdim
1156303231Sdim  /// Check Err. If it's in a failure state log the error(s) and exit.
1157303231Sdim  void operator()(Error Err) const { checkError(std::move(Err)); }
1158303231Sdim
1159303231Sdim  /// Check E. If it's in a success state then return the contained value. If
1160303231Sdim  /// it's in a failure state log the error(s) and exit.
1161303231Sdim  template <typename T> T operator()(Expected<T> &&E) const {
1162303231Sdim    checkError(E.takeError());
1163303231Sdim    return std::move(*E);
1164303231Sdim  }
1165303231Sdim
1166303231Sdim  /// Check E. If it's in a success state then return the contained reference. If
1167303231Sdim  /// it's in a failure state log the error(s) and exit.
1168303231Sdim  template <typename T> T& operator()(Expected<T&> &&E) const {
1169303231Sdim    checkError(E.takeError());
1170303231Sdim    return *E;
1171303231Sdim  }
1172303231Sdim
1173303231Sdimprivate:
1174303231Sdim  void checkError(Error Err) const {
1175303231Sdim    if (Err) {
1176303231Sdim      int ExitCode = GetExitCode(Err);
1177303231Sdim      logAllUnhandledErrors(std::move(Err), errs(), Banner);
1178303231Sdim      exit(ExitCode);
1179303231Sdim    }
1180303231Sdim  }
1181303231Sdim
1182303231Sdim  std::string Banner;
1183303231Sdim  std::function<int(const Error &)> GetExitCode;
1184303231Sdim};
1185303231Sdim
1186314564Sdim} // end namespace llvm
1187303231Sdim
1188303231Sdim#endif // LLVM_SUPPORT_ERROR_H
1189