1321369Sdim//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
2303231Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6303231Sdim//
7303231Sdim//===----------------------------------------------------------------------===//
8303231Sdim//
9303231Sdim// This file defines an API used to report recoverable errors.
10303231Sdim//
11303231Sdim//===----------------------------------------------------------------------===//
12303231Sdim
13303231Sdim#ifndef LLVM_SUPPORT_ERROR_H
14303231Sdim#define LLVM_SUPPORT_ERROR_H
15303231Sdim
16344779Sdim#include "llvm-c/Error.h"
17344779Sdim#include "llvm/ADT/STLExtras.h"
18314564Sdim#include "llvm/ADT/SmallVector.h"
19303231Sdim#include "llvm/ADT/StringExtras.h"
20303231Sdim#include "llvm/ADT/Twine.h"
21314564Sdim#include "llvm/Config/abi-breaking.h"
22314564Sdim#include "llvm/Support/AlignOf.h"
23314564Sdim#include "llvm/Support/Compiler.h"
24303231Sdim#include "llvm/Support/Debug.h"
25321369Sdim#include "llvm/Support/ErrorHandling.h"
26303231Sdim#include "llvm/Support/ErrorOr.h"
27341825Sdim#include "llvm/Support/Format.h"
28303231Sdim#include "llvm/Support/raw_ostream.h"
29314564Sdim#include <algorithm>
30314564Sdim#include <cassert>
31314564Sdim#include <cstdint>
32314564Sdim#include <cstdlib>
33314564Sdim#include <functional>
34314564Sdim#include <memory>
35314564Sdim#include <new>
36314564Sdim#include <string>
37314564Sdim#include <system_error>
38314564Sdim#include <type_traits>
39314564Sdim#include <utility>
40303231Sdim#include <vector>
41303231Sdim
42303231Sdimnamespace llvm {
43303231Sdim
44314564Sdimclass ErrorSuccess;
45303231Sdim
46303231Sdim/// Base class for error info classes. Do not extend this directly: Extend
47303231Sdim/// the ErrorInfo template subclass instead.
48303231Sdimclass ErrorInfoBase {
49303231Sdimpublic:
50314564Sdim  virtual ~ErrorInfoBase() = default;
51303231Sdim
52303231Sdim  /// Print an error message to an output stream.
53303231Sdim  virtual void log(raw_ostream &OS) const = 0;
54303231Sdim
55303231Sdim  /// Return the error message as a string.
56303231Sdim  virtual std::string message() const {
57303231Sdim    std::string Msg;
58303231Sdim    raw_string_ostream OS(Msg);
59303231Sdim    log(OS);
60303231Sdim    return OS.str();
61303231Sdim  }
62303231Sdim
63303231Sdim  /// Convert this error to a std::error_code.
64303231Sdim  ///
65303231Sdim  /// This is a temporary crutch to enable interaction with code still
66303231Sdim  /// using std::error_code. It will be removed in the future.
67303231Sdim  virtual std::error_code convertToErrorCode() const = 0;
68303231Sdim
69321369Sdim  // Returns the class ID for this type.
70321369Sdim  static const void *classID() { return &ID; }
71321369Sdim
72321369Sdim  // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
73321369Sdim  virtual const void *dynamicClassID() const = 0;
74321369Sdim
75303231Sdim  // Check whether this instance is a subclass of the class identified by
76303231Sdim  // ClassID.
77303231Sdim  virtual bool isA(const void *const ClassID) const {
78303231Sdim    return ClassID == classID();
79303231Sdim  }
80303231Sdim
81303231Sdim  // Check whether this instance is a subclass of ErrorInfoT.
82303231Sdim  template <typename ErrorInfoT> bool isA() const {
83303231Sdim    return isA(ErrorInfoT::classID());
84303231Sdim  }
85303231Sdim
86303231Sdimprivate:
87303231Sdim  virtual void anchor();
88314564Sdim
89303231Sdim  static char ID;
90303231Sdim};
91303231Sdim
92303231Sdim/// Lightweight error class with error context and mandatory checking.
93303231Sdim///
94303231Sdim/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
95303231Sdim/// are represented by setting the pointer to a ErrorInfoBase subclass
96303231Sdim/// instance containing information describing the failure. Success is
97303231Sdim/// represented by a null pointer value.
98303231Sdim///
99303231Sdim/// Instances of Error also contains a 'Checked' flag, which must be set
100303231Sdim/// before the destructor is called, otherwise the destructor will trigger a
101303231Sdim/// runtime error. This enforces at runtime the requirement that all Error
102303231Sdim/// instances be checked or returned to the caller.
103303231Sdim///
104303231Sdim/// There are two ways to set the checked flag, depending on what state the
105303231Sdim/// Error instance is in. For Error instances indicating success, it
106303231Sdim/// is sufficient to invoke the boolean conversion operator. E.g.:
107303231Sdim///
108314564Sdim///   @code{.cpp}
109303231Sdim///   Error foo(<...>);
110303231Sdim///
111303231Sdim///   if (auto E = foo(<...>))
112303231Sdim///     return E; // <- Return E if it is in the error state.
113303231Sdim///   // We have verified that E was in the success state. It can now be safely
114303231Sdim///   // destroyed.
115314564Sdim///   @endcode
116303231Sdim///
117303231Sdim/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
118303231Sdim/// without testing the return value will raise a runtime error, even if foo
119303231Sdim/// returns success.
120303231Sdim///
121303231Sdim/// For Error instances representing failure, you must use either the
122303231Sdim/// handleErrors or handleAllErrors function with a typed handler. E.g.:
123303231Sdim///
124314564Sdim///   @code{.cpp}
125303231Sdim///   class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
126303231Sdim///     // Custom error info.
127303231Sdim///   };
128303231Sdim///
129303231Sdim///   Error foo(<...>) { return make_error<MyErrorInfo>(...); }
130303231Sdim///
131303231Sdim///   auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
132303231Sdim///   auto NewE =
133303231Sdim///     handleErrors(E,
134303231Sdim///       [](const MyErrorInfo &M) {
135303231Sdim///         // Deal with the error.
136303231Sdim///       },
137303231Sdim///       [](std::unique_ptr<OtherError> M) -> Error {
138303231Sdim///         if (canHandle(*M)) {
139303231Sdim///           // handle error.
140303231Sdim///           return Error::success();
141303231Sdim///         }
142303231Sdim///         // Couldn't handle this error instance. Pass it up the stack.
143303231Sdim///         return Error(std::move(M));
144303231Sdim///       );
145303231Sdim///   // Note - we must check or return NewE in case any of the handlers
146303231Sdim///   // returned a new error.
147314564Sdim///   @endcode
148303231Sdim///
149303231Sdim/// The handleAllErrors function is identical to handleErrors, except
150303231Sdim/// that it has a void return type, and requires all errors to be handled and
151303231Sdim/// no new errors be returned. It prevents errors (assuming they can all be
152303231Sdim/// handled) from having to be bubbled all the way to the top-level.
153303231Sdim///
154303231Sdim/// *All* Error instances must be checked before destruction, even if
155303231Sdim/// they're moved-assigned or constructed from Success values that have already
156303231Sdim/// been checked. This enforces checking through all levels of the call stack.
157314564Sdimclass LLVM_NODISCARD Error {
158360784Sdim  // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors
159360784Sdim  // to add to the error list. It can't rely on handleErrors for this, since
160360784Sdim  // handleErrors does not support ErrorList handlers.
161303231Sdim  friend class ErrorList;
162303231Sdim
163303231Sdim  // handleErrors needs to be able to set the Checked flag.
164303231Sdim  template <typename... HandlerTs>
165303231Sdim  friend Error handleErrors(Error E, HandlerTs &&... Handlers);
166303231Sdim
167303231Sdim  // Expected<T> needs to be able to steal the payload when constructed from an
168303231Sdim  // error.
169314564Sdim  template <typename T> friend class Expected;
170303231Sdim
171344779Sdim  // wrap needs to be able to steal the payload.
172344779Sdim  friend LLVMErrorRef wrap(Error);
173344779Sdim
174314564Sdimprotected:
175303231Sdim  /// Create a success value. Prefer using 'Error::success()' for readability
176321369Sdim  Error() {
177303231Sdim    setPtr(nullptr);
178303231Sdim    setChecked(false);
179303231Sdim  }
180303231Sdim
181314564Sdimpublic:
182314564Sdim  /// Create a success value.
183314564Sdim  static ErrorSuccess success();
184303231Sdim
185303231Sdim  // Errors are not copy-constructable.
186303231Sdim  Error(const Error &Other) = delete;
187303231Sdim
188303231Sdim  /// Move-construct an error value. The newly constructed error is considered
189303231Sdim  /// unchecked, even if the source error had been checked. The original error
190303231Sdim  /// becomes a checked Success value, regardless of its original state.
191321369Sdim  Error(Error &&Other) {
192303231Sdim    setChecked(true);
193303231Sdim    *this = std::move(Other);
194303231Sdim  }
195303231Sdim
196303231Sdim  /// Create an error value. Prefer using the 'make_error' function, but
197303231Sdim  /// this constructor can be useful when "re-throwing" errors from handlers.
198303231Sdim  Error(std::unique_ptr<ErrorInfoBase> Payload) {
199303231Sdim    setPtr(Payload.release());
200303231Sdim    setChecked(false);
201303231Sdim  }
202303231Sdim
203303231Sdim  // Errors are not copy-assignable.
204303231Sdim  Error &operator=(const Error &Other) = delete;
205303231Sdim
206303231Sdim  /// Move-assign an error value. The current error must represent success, you
207303231Sdim  /// you cannot overwrite an unhandled error. The current error is then
208303231Sdim  /// considered unchecked. The source error becomes a checked success value,
209303231Sdim  /// regardless of its original state.
210303231Sdim  Error &operator=(Error &&Other) {
211303231Sdim    // Don't allow overwriting of unchecked values.
212303231Sdim    assertIsChecked();
213303231Sdim    setPtr(Other.getPtr());
214303231Sdim
215303231Sdim    // This Error is unchecked, even if the source error was checked.
216303231Sdim    setChecked(false);
217303231Sdim
218303231Sdim    // Null out Other's payload and set its checked bit.
219303231Sdim    Other.setPtr(nullptr);
220303231Sdim    Other.setChecked(true);
221303231Sdim
222303231Sdim    return *this;
223303231Sdim  }
224303231Sdim
225303231Sdim  /// Destroy a Error. Fails with a call to abort() if the error is
226303231Sdim  /// unchecked.
227303231Sdim  ~Error() {
228303231Sdim    assertIsChecked();
229303231Sdim    delete getPtr();
230303231Sdim  }
231303231Sdim
232303231Sdim  /// Bool conversion. Returns true if this Error is in a failure state,
233303231Sdim  /// and false if it is in an accept state. If the error is in a Success state
234303231Sdim  /// it will be considered checked.
235303231Sdim  explicit operator bool() {
236303231Sdim    setChecked(getPtr() == nullptr);
237303231Sdim    return getPtr() != nullptr;
238303231Sdim  }
239303231Sdim
240303231Sdim  /// Check whether one error is a subclass of another.
241303231Sdim  template <typename ErrT> bool isA() const {
242303231Sdim    return getPtr() && getPtr()->isA(ErrT::classID());
243303231Sdim  }
244303231Sdim
245321369Sdim  /// Returns the dynamic class id of this error, or null if this is a success
246321369Sdim  /// value.
247321369Sdim  const void* dynamicClassID() const {
248321369Sdim    if (!getPtr())
249321369Sdim      return nullptr;
250321369Sdim    return getPtr()->dynamicClassID();
251321369Sdim  }
252321369Sdim
253303231Sdimprivate:
254327952Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
255327952Sdim  // assertIsChecked() happens very frequently, but under normal circumstances
256327952Sdim  // is supposed to be a no-op.  So we want it to be inlined, but having a bunch
257327952Sdim  // of debug prints can cause the function to be too large for inlining.  So
258327952Sdim  // it's important that we define this function out of line so that it can't be
259327952Sdim  // inlined.
260327952Sdim  LLVM_ATTRIBUTE_NORETURN
261327952Sdim  void fatalUncheckedError() const;
262327952Sdim#endif
263327952Sdim
264303231Sdim  void assertIsChecked() {
265314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
266327952Sdim    if (LLVM_UNLIKELY(!getChecked() || getPtr()))
267327952Sdim      fatalUncheckedError();
268303231Sdim#endif
269303231Sdim  }
270303231Sdim
271303231Sdim  ErrorInfoBase *getPtr() const {
272314564Sdim    return reinterpret_cast<ErrorInfoBase*>(
273314564Sdim             reinterpret_cast<uintptr_t>(Payload) &
274314564Sdim             ~static_cast<uintptr_t>(0x1));
275303231Sdim  }
276303231Sdim
277303231Sdim  void setPtr(ErrorInfoBase *EI) {
278314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
279314564Sdim    Payload = reinterpret_cast<ErrorInfoBase*>(
280314564Sdim                (reinterpret_cast<uintptr_t>(EI) &
281314564Sdim                 ~static_cast<uintptr_t>(0x1)) |
282314564Sdim                (reinterpret_cast<uintptr_t>(Payload) & 0x1));
283303231Sdim#else
284303231Sdim    Payload = EI;
285303231Sdim#endif
286303231Sdim  }
287303231Sdim
288303231Sdim  bool getChecked() const {
289314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
290314564Sdim    return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
291303231Sdim#else
292303231Sdim    return true;
293303231Sdim#endif
294303231Sdim  }
295303231Sdim
296303231Sdim  void setChecked(bool V) {
297314564Sdim    Payload = reinterpret_cast<ErrorInfoBase*>(
298314564Sdim                (reinterpret_cast<uintptr_t>(Payload) &
299314564Sdim                  ~static_cast<uintptr_t>(0x1)) |
300314564Sdim                  (V ? 0 : 1));
301303231Sdim  }
302303231Sdim
303303231Sdim  std::unique_ptr<ErrorInfoBase> takePayload() {
304303231Sdim    std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
305303231Sdim    setPtr(nullptr);
306303231Sdim    setChecked(true);
307303231Sdim    return Tmp;
308303231Sdim  }
309303231Sdim
310341825Sdim  friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
311341825Sdim    if (auto P = E.getPtr())
312341825Sdim      P->log(OS);
313341825Sdim    else
314341825Sdim      OS << "success";
315341825Sdim    return OS;
316341825Sdim  }
317341825Sdim
318321369Sdim  ErrorInfoBase *Payload = nullptr;
319303231Sdim};
320303231Sdim
321314564Sdim/// Subclass of Error for the sole purpose of identifying the success path in
322314564Sdim/// the type system. This allows to catch invalid conversion to Expected<T> at
323314564Sdim/// compile time.
324344779Sdimclass ErrorSuccess final : public Error {};
325314564Sdim
326314564Sdiminline ErrorSuccess Error::success() { return ErrorSuccess(); }
327314564Sdim
328303231Sdim/// Make a Error instance representing failure using the given error info
329303231Sdim/// type.
330303231Sdimtemplate <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
331360784Sdim  return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
332303231Sdim}
333303231Sdim
334303231Sdim/// Base class for user error types. Users should declare their error types
335303231Sdim/// like:
336303231Sdim///
337303231Sdim/// class MyError : public ErrorInfo<MyError> {
338303231Sdim///   ....
339303231Sdim/// };
340303231Sdim///
341303231Sdim/// This class provides an implementation of the ErrorInfoBase::kind
342303231Sdim/// method, which is used by the Error RTTI system.
343303231Sdimtemplate <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
344303231Sdimclass ErrorInfo : public ParentErrT {
345303231Sdimpublic:
346344779Sdim  using ParentErrT::ParentErrT; // inherit constructors
347344779Sdim
348321369Sdim  static const void *classID() { return &ThisErrT::ID; }
349321369Sdim
350321369Sdim  const void *dynamicClassID() const override { return &ThisErrT::ID; }
351321369Sdim
352303231Sdim  bool isA(const void *const ClassID) const override {
353303231Sdim    return ClassID == classID() || ParentErrT::isA(ClassID);
354303231Sdim  }
355303231Sdim};
356303231Sdim
357303231Sdim/// Special ErrorInfo subclass representing a list of ErrorInfos.
358303231Sdim/// Instances of this class are constructed by joinError.
359303231Sdimclass ErrorList final : public ErrorInfo<ErrorList> {
360303231Sdim  // handleErrors needs to be able to iterate the payload list of an
361303231Sdim  // ErrorList.
362303231Sdim  template <typename... HandlerTs>
363303231Sdim  friend Error handleErrors(Error E, HandlerTs &&... Handlers);
364303231Sdim
365303231Sdim  // joinErrors is implemented in terms of join.
366303231Sdim  friend Error joinErrors(Error, Error);
367303231Sdim
368303231Sdimpublic:
369303231Sdim  void log(raw_ostream &OS) const override {
370303231Sdim    OS << "Multiple errors:\n";
371303231Sdim    for (auto &ErrPayload : Payloads) {
372303231Sdim      ErrPayload->log(OS);
373303231Sdim      OS << "\n";
374303231Sdim    }
375303231Sdim  }
376303231Sdim
377303231Sdim  std::error_code convertToErrorCode() const override;
378303231Sdim
379303231Sdim  // Used by ErrorInfo::classID.
380303231Sdim  static char ID;
381303231Sdim
382303231Sdimprivate:
383303231Sdim  ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
384303231Sdim            std::unique_ptr<ErrorInfoBase> Payload2) {
385303231Sdim    assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
386303231Sdim           "ErrorList constructor payloads should be singleton errors");
387303231Sdim    Payloads.push_back(std::move(Payload1));
388303231Sdim    Payloads.push_back(std::move(Payload2));
389303231Sdim  }
390303231Sdim
391303231Sdim  static Error join(Error E1, Error E2) {
392303231Sdim    if (!E1)
393303231Sdim      return E2;
394303231Sdim    if (!E2)
395303231Sdim      return E1;
396303231Sdim    if (E1.isA<ErrorList>()) {
397303231Sdim      auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
398303231Sdim      if (E2.isA<ErrorList>()) {
399303231Sdim        auto E2Payload = E2.takePayload();
400303231Sdim        auto &E2List = static_cast<ErrorList &>(*E2Payload);
401303231Sdim        for (auto &Payload : E2List.Payloads)
402303231Sdim          E1List.Payloads.push_back(std::move(Payload));
403303231Sdim      } else
404303231Sdim        E1List.Payloads.push_back(E2.takePayload());
405303231Sdim
406303231Sdim      return E1;
407303231Sdim    }
408303231Sdim    if (E2.isA<ErrorList>()) {
409303231Sdim      auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
410303231Sdim      E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
411303231Sdim      return E2;
412303231Sdim    }
413303231Sdim    return Error(std::unique_ptr<ErrorList>(
414303231Sdim        new ErrorList(E1.takePayload(), E2.takePayload())));
415303231Sdim  }
416303231Sdim
417303231Sdim  std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
418303231Sdim};
419303231Sdim
420303231Sdim/// Concatenate errors. The resulting Error is unchecked, and contains the
421303231Sdim/// ErrorInfo(s), if any, contained in E1, followed by the
422303231Sdim/// ErrorInfo(s), if any, contained in E2.
423303231Sdiminline Error joinErrors(Error E1, Error E2) {
424303231Sdim  return ErrorList::join(std::move(E1), std::move(E2));
425303231Sdim}
426303231Sdim
427303231Sdim/// Tagged union holding either a T or a Error.
428303231Sdim///
429303231Sdim/// This class parallels ErrorOr, but replaces error_code with Error. Since
430303231Sdim/// Error cannot be copied, this class replaces getError() with
431303231Sdim/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
432303231Sdim/// error class type.
433314564Sdimtemplate <class T> class LLVM_NODISCARD Expected {
434321369Sdim  template <class T1> friend class ExpectedAsOutParameter;
435303231Sdim  template <class OtherT> friend class Expected;
436321369Sdim
437303231Sdim  static const bool isRef = std::is_reference<T>::value;
438303231Sdim
439341825Sdim  using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
440303231Sdim
441321369Sdim  using error_type = std::unique_ptr<ErrorInfoBase>;
442321369Sdim
443303231Sdimpublic:
444321369Sdim  using storage_type = typename std::conditional<isRef, wrap, T>::type;
445321369Sdim  using value_type = T;
446303231Sdim
447303231Sdimprivate:
448321369Sdim  using reference = typename std::remove_reference<T>::type &;
449321369Sdim  using const_reference = const typename std::remove_reference<T>::type &;
450321369Sdim  using pointer = typename std::remove_reference<T>::type *;
451321369Sdim  using const_pointer = const typename std::remove_reference<T>::type *;
452303231Sdim
453303231Sdimpublic:
454303231Sdim  /// Create an Expected<T> error value from the given Error.
455303231Sdim  Expected(Error Err)
456303231Sdim      : HasError(true)
457314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
458314564Sdim        // Expected is unchecked upon construction in Debug builds.
459314564Sdim        , Unchecked(true)
460303231Sdim#endif
461303231Sdim  {
462303231Sdim    assert(Err && "Cannot create Expected<T> from Error success value.");
463314564Sdim    new (getErrorStorage()) error_type(Err.takePayload());
464303231Sdim  }
465303231Sdim
466314564Sdim  /// Forbid to convert from Error::success() implicitly, this avoids having
467314564Sdim  /// Expected<T> foo() { return Error::success(); } which compiles otherwise
468314564Sdim  /// but triggers the assertion above.
469314564Sdim  Expected(ErrorSuccess) = delete;
470314564Sdim
471303231Sdim  /// Create an Expected<T> success value from the given OtherT value, which
472303231Sdim  /// must be convertible to T.
473303231Sdim  template <typename OtherT>
474303231Sdim  Expected(OtherT &&Val,
475303231Sdim           typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
476303231Sdim               * = nullptr)
477303231Sdim      : HasError(false)
478314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
479314564Sdim        // Expected is unchecked upon construction in Debug builds.
480314564Sdim        , Unchecked(true)
481303231Sdim#endif
482303231Sdim  {
483303231Sdim    new (getStorage()) storage_type(std::forward<OtherT>(Val));
484303231Sdim  }
485303231Sdim
486303231Sdim  /// Move construct an Expected<T> value.
487303231Sdim  Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
488303231Sdim
489303231Sdim  /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
490303231Sdim  /// must be convertible to T.
491303231Sdim  template <class OtherT>
492303231Sdim  Expected(Expected<OtherT> &&Other,
493303231Sdim           typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
494303231Sdim               * = nullptr) {
495303231Sdim    moveConstruct(std::move(Other));
496303231Sdim  }
497303231Sdim
498303231Sdim  /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
499303231Sdim  /// isn't convertible to T.
500303231Sdim  template <class OtherT>
501303231Sdim  explicit Expected(
502303231Sdim      Expected<OtherT> &&Other,
503303231Sdim      typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
504303231Sdim          nullptr) {
505303231Sdim    moveConstruct(std::move(Other));
506303231Sdim  }
507303231Sdim
508303231Sdim  /// Move-assign from another Expected<T>.
509303231Sdim  Expected &operator=(Expected &&Other) {
510303231Sdim    moveAssign(std::move(Other));
511303231Sdim    return *this;
512303231Sdim  }
513303231Sdim
514303231Sdim  /// Destroy an Expected<T>.
515303231Sdim  ~Expected() {
516303231Sdim    assertIsChecked();
517303231Sdim    if (!HasError)
518303231Sdim      getStorage()->~storage_type();
519303231Sdim    else
520303231Sdim      getErrorStorage()->~error_type();
521303231Sdim  }
522303231Sdim
523341825Sdim  /// Return false if there is an error.
524303231Sdim  explicit operator bool() {
525314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
526314564Sdim    Unchecked = HasError;
527303231Sdim#endif
528303231Sdim    return !HasError;
529303231Sdim  }
530303231Sdim
531341825Sdim  /// Returns a reference to the stored T value.
532303231Sdim  reference get() {
533303231Sdim    assertIsChecked();
534303231Sdim    return *getStorage();
535303231Sdim  }
536303231Sdim
537341825Sdim  /// Returns a const reference to the stored T value.
538303231Sdim  const_reference get() const {
539303231Sdim    assertIsChecked();
540303231Sdim    return const_cast<Expected<T> *>(this)->get();
541303231Sdim  }
542303231Sdim
543341825Sdim  /// Check that this Expected<T> is an error of type ErrT.
544303231Sdim  template <typename ErrT> bool errorIsA() const {
545321369Sdim    return HasError && (*getErrorStorage())->template isA<ErrT>();
546303231Sdim  }
547303231Sdim
548341825Sdim  /// Take ownership of the stored error.
549303231Sdim  /// After calling this the Expected<T> is in an indeterminate state that can
550303231Sdim  /// only be safely destructed. No further calls (beside the destructor) should
551360784Sdim  /// be made on the Expected<T> value.
552303231Sdim  Error takeError() {
553314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
554314564Sdim    Unchecked = false;
555303231Sdim#endif
556303231Sdim    return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
557303231Sdim  }
558303231Sdim
559341825Sdim  /// Returns a pointer to the stored T value.
560303231Sdim  pointer operator->() {
561303231Sdim    assertIsChecked();
562303231Sdim    return toPointer(getStorage());
563303231Sdim  }
564303231Sdim
565341825Sdim  /// Returns a const pointer to the stored T value.
566303231Sdim  const_pointer operator->() const {
567303231Sdim    assertIsChecked();
568303231Sdim    return toPointer(getStorage());
569303231Sdim  }
570303231Sdim
571341825Sdim  /// Returns a reference to the stored T value.
572303231Sdim  reference operator*() {
573303231Sdim    assertIsChecked();
574303231Sdim    return *getStorage();
575303231Sdim  }
576303231Sdim
577341825Sdim  /// Returns a const reference to the stored T value.
578303231Sdim  const_reference operator*() const {
579303231Sdim    assertIsChecked();
580303231Sdim    return *getStorage();
581303231Sdim  }
582303231Sdim
583303231Sdimprivate:
584303231Sdim  template <class T1>
585303231Sdim  static bool compareThisIfSameType(const T1 &a, const T1 &b) {
586303231Sdim    return &a == &b;
587303231Sdim  }
588303231Sdim
589303231Sdim  template <class T1, class T2>
590303231Sdim  static bool compareThisIfSameType(const T1 &a, const T2 &b) {
591303231Sdim    return false;
592303231Sdim  }
593303231Sdim
594303231Sdim  template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
595303231Sdim    HasError = Other.HasError;
596314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
597314564Sdim    Unchecked = true;
598314564Sdim    Other.Unchecked = false;
599303231Sdim#endif
600303231Sdim
601303231Sdim    if (!HasError)
602303231Sdim      new (getStorage()) storage_type(std::move(*Other.getStorage()));
603303231Sdim    else
604303231Sdim      new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
605303231Sdim  }
606303231Sdim
607303231Sdim  template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
608303231Sdim    assertIsChecked();
609303231Sdim
610303231Sdim    if (compareThisIfSameType(*this, Other))
611303231Sdim      return;
612303231Sdim
613303231Sdim    this->~Expected();
614303231Sdim    new (this) Expected(std::move(Other));
615303231Sdim  }
616303231Sdim
617303231Sdim  pointer toPointer(pointer Val) { return Val; }
618303231Sdim
619303231Sdim  const_pointer toPointer(const_pointer Val) const { return Val; }
620303231Sdim
621303231Sdim  pointer toPointer(wrap *Val) { return &Val->get(); }
622303231Sdim
623303231Sdim  const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
624303231Sdim
625303231Sdim  storage_type *getStorage() {
626303231Sdim    assert(!HasError && "Cannot get value when an error exists!");
627303231Sdim    return reinterpret_cast<storage_type *>(TStorage.buffer);
628303231Sdim  }
629303231Sdim
630303231Sdim  const storage_type *getStorage() const {
631303231Sdim    assert(!HasError && "Cannot get value when an error exists!");
632303231Sdim    return reinterpret_cast<const storage_type *>(TStorage.buffer);
633303231Sdim  }
634303231Sdim
635303231Sdim  error_type *getErrorStorage() {
636303231Sdim    assert(HasError && "Cannot get error when a value exists!");
637303231Sdim    return reinterpret_cast<error_type *>(ErrorStorage.buffer);
638303231Sdim  }
639303231Sdim
640321369Sdim  const error_type *getErrorStorage() const {
641321369Sdim    assert(HasError && "Cannot get error when a value exists!");
642321369Sdim    return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
643321369Sdim  }
644321369Sdim
645321369Sdim  // Used by ExpectedAsOutParameter to reset the checked flag.
646321369Sdim  void setUnchecked() {
647321369Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
648321369Sdim    Unchecked = true;
649321369Sdim#endif
650321369Sdim  }
651321369Sdim
652327952Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
653327952Sdim  LLVM_ATTRIBUTE_NORETURN
654327952Sdim  LLVM_ATTRIBUTE_NOINLINE
655327952Sdim  void fatalUncheckedExpected() const {
656327952Sdim    dbgs() << "Expected<T> must be checked before access or destruction.\n";
657327952Sdim    if (HasError) {
658327952Sdim      dbgs() << "Unchecked Expected<T> contained error:\n";
659327952Sdim      (*getErrorStorage())->log(dbgs());
660327952Sdim    } else
661327952Sdim      dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
662327952Sdim                "values in success mode must still be checked prior to being "
663327952Sdim                "destroyed).\n";
664327952Sdim    abort();
665327952Sdim  }
666327952Sdim#endif
667327952Sdim
668303231Sdim  void assertIsChecked() {
669314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
670327952Sdim    if (LLVM_UNLIKELY(Unchecked))
671327952Sdim      fatalUncheckedExpected();
672303231Sdim#endif
673303231Sdim  }
674303231Sdim
675303231Sdim  union {
676303231Sdim    AlignedCharArrayUnion<storage_type> TStorage;
677303231Sdim    AlignedCharArrayUnion<error_type> ErrorStorage;
678303231Sdim  };
679303231Sdim  bool HasError : 1;
680314564Sdim#if LLVM_ENABLE_ABI_BREAKING_CHECKS
681314564Sdim  bool Unchecked : 1;
682303231Sdim#endif
683303231Sdim};
684303231Sdim
685327952Sdim/// Report a serious error, calling any installed error handler. See
686327952Sdim/// ErrorHandling.h.
687327952SdimLLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err,
688327952Sdim                                                bool gen_crash_diag = true);
689327952Sdim
690327952Sdim/// Report a fatal error if Err is a failure value.
691327952Sdim///
692327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it
693327952Sdim/// is known that the Error will always be a success value. E.g.
694327952Sdim///
695327952Sdim///   @code{.cpp}
696327952Sdim///   // foo only attempts the fallible operation if DoFallibleOperation is
697327952Sdim///   // true. If DoFallibleOperation is false then foo always returns
698327952Sdim///   // Error::success().
699327952Sdim///   Error foo(bool DoFallibleOperation);
700327952Sdim///
701327952Sdim///   cantFail(foo(false));
702327952Sdim///   @endcode
703327952Sdiminline void cantFail(Error Err, const char *Msg = nullptr) {
704327952Sdim  if (Err) {
705327952Sdim    if (!Msg)
706327952Sdim      Msg = "Failure value returned from cantFail wrapped call";
707360784Sdim#ifndef NDEBUG
708360784Sdim    std::string Str;
709360784Sdim    raw_string_ostream OS(Str);
710360784Sdim    OS << Msg << "\n" << Err;
711360784Sdim    Msg = OS.str().c_str();
712360784Sdim#endif
713327952Sdim    llvm_unreachable(Msg);
714327952Sdim  }
715327952Sdim}
716327952Sdim
717327952Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
718327952Sdim/// returns the contained value.
719327952Sdim///
720327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it
721327952Sdim/// is known that the Error will always be a success value. E.g.
722327952Sdim///
723327952Sdim///   @code{.cpp}
724327952Sdim///   // foo only attempts the fallible operation if DoFallibleOperation is
725327952Sdim///   // true. If DoFallibleOperation is false then foo always returns an int.
726327952Sdim///   Expected<int> foo(bool DoFallibleOperation);
727327952Sdim///
728327952Sdim///   int X = cantFail(foo(false));
729327952Sdim///   @endcode
730327952Sdimtemplate <typename T>
731327952SdimT cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
732327952Sdim  if (ValOrErr)
733327952Sdim    return std::move(*ValOrErr);
734327952Sdim  else {
735327952Sdim    if (!Msg)
736327952Sdim      Msg = "Failure value returned from cantFail wrapped call";
737360784Sdim#ifndef NDEBUG
738360784Sdim    std::string Str;
739360784Sdim    raw_string_ostream OS(Str);
740360784Sdim    auto E = ValOrErr.takeError();
741360784Sdim    OS << Msg << "\n" << E;
742360784Sdim    Msg = OS.str().c_str();
743360784Sdim#endif
744327952Sdim    llvm_unreachable(Msg);
745327952Sdim  }
746327952Sdim}
747327952Sdim
748327952Sdim/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
749327952Sdim/// returns the contained reference.
750327952Sdim///
751327952Sdim/// This function can be used to wrap calls to fallible functions ONLY when it
752327952Sdim/// is known that the Error will always be a success value. E.g.
753327952Sdim///
754327952Sdim///   @code{.cpp}
755327952Sdim///   // foo only attempts the fallible operation if DoFallibleOperation is
756327952Sdim///   // true. If DoFallibleOperation is false then foo always returns a Bar&.
757327952Sdim///   Expected<Bar&> foo(bool DoFallibleOperation);
758327952Sdim///
759327952Sdim///   Bar &X = cantFail(foo(false));
760327952Sdim///   @endcode
761327952Sdimtemplate <typename T>
762327952SdimT& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
763327952Sdim  if (ValOrErr)
764327952Sdim    return *ValOrErr;
765327952Sdim  else {
766327952Sdim    if (!Msg)
767327952Sdim      Msg = "Failure value returned from cantFail wrapped call";
768360784Sdim#ifndef NDEBUG
769360784Sdim    std::string Str;
770360784Sdim    raw_string_ostream OS(Str);
771360784Sdim    auto E = ValOrErr.takeError();
772360784Sdim    OS << Msg << "\n" << E;
773360784Sdim    Msg = OS.str().c_str();
774360784Sdim#endif
775327952Sdim    llvm_unreachable(Msg);
776327952Sdim  }
777327952Sdim}
778327952Sdim
779327952Sdim/// Helper for testing applicability of, and applying, handlers for
780327952Sdim/// ErrorInfo types.
781327952Sdimtemplate <typename HandlerT>
782327952Sdimclass ErrorHandlerTraits
783327952Sdim    : public ErrorHandlerTraits<decltype(
784327952Sdim          &std::remove_reference<HandlerT>::type::operator())> {};
785327952Sdim
786327952Sdim// Specialization functions of the form 'Error (const ErrT&)'.
787327952Sdimtemplate <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
788327952Sdimpublic:
789327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
790327952Sdim    return E.template isA<ErrT>();
791327952Sdim  }
792327952Sdim
793327952Sdim  template <typename HandlerT>
794327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
795327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
796327952Sdim    return H(static_cast<ErrT &>(*E));
797327952Sdim  }
798327952Sdim};
799327952Sdim
800327952Sdim// Specialization functions of the form 'void (const ErrT&)'.
801327952Sdimtemplate <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
802327952Sdimpublic:
803327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
804327952Sdim    return E.template isA<ErrT>();
805327952Sdim  }
806327952Sdim
807327952Sdim  template <typename HandlerT>
808327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
809327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
810327952Sdim    H(static_cast<ErrT &>(*E));
811327952Sdim    return Error::success();
812327952Sdim  }
813327952Sdim};
814327952Sdim
815327952Sdim/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
816327952Sdimtemplate <typename ErrT>
817327952Sdimclass ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
818327952Sdimpublic:
819327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
820327952Sdim    return E.template isA<ErrT>();
821327952Sdim  }
822327952Sdim
823327952Sdim  template <typename HandlerT>
824327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
825327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
826327952Sdim    std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
827327952Sdim    return H(std::move(SubE));
828327952Sdim  }
829327952Sdim};
830327952Sdim
831327952Sdim/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
832327952Sdimtemplate <typename ErrT>
833327952Sdimclass ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
834327952Sdimpublic:
835327952Sdim  static bool appliesTo(const ErrorInfoBase &E) {
836327952Sdim    return E.template isA<ErrT>();
837327952Sdim  }
838327952Sdim
839327952Sdim  template <typename HandlerT>
840327952Sdim  static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
841327952Sdim    assert(appliesTo(*E) && "Applying incorrect handler");
842327952Sdim    std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
843327952Sdim    H(std::move(SubE));
844327952Sdim    return Error::success();
845327952Sdim  }
846327952Sdim};
847327952Sdim
848327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'.
849327952Sdimtemplate <typename C, typename RetT, typename ErrT>
850327952Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &)>
851327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
852327952Sdim
853327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'.
854327952Sdimtemplate <typename C, typename RetT, typename ErrT>
855327952Sdimclass ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
856327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
857327952Sdim
858327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&)'.
859327952Sdimtemplate <typename C, typename RetT, typename ErrT>
860327952Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
861327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
862327952Sdim
863327952Sdim// Specialization for member functions of the form 'RetT (const ErrT&) const'.
864327952Sdimtemplate <typename C, typename RetT, typename ErrT>
865327952Sdimclass ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
866327952Sdim    : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
867327952Sdim
868327952Sdim/// Specialization for member functions of the form
869327952Sdim/// 'RetT (std::unique_ptr<ErrT>)'.
870327952Sdimtemplate <typename C, typename RetT, typename ErrT>
871327952Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
872327952Sdim    : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
873327952Sdim
874327952Sdim/// Specialization for member functions of the form
875327952Sdim/// 'RetT (std::unique_ptr<ErrT>) const'.
876327952Sdimtemplate <typename C, typename RetT, typename ErrT>
877327952Sdimclass ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
878327952Sdim    : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
879327952Sdim
880327952Sdiminline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
881327952Sdim  return Error(std::move(Payload));
882327952Sdim}
883327952Sdim
884327952Sdimtemplate <typename HandlerT, typename... HandlerTs>
885327952SdimError handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
886327952Sdim                      HandlerT &&Handler, HandlerTs &&... Handlers) {
887327952Sdim  if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
888327952Sdim    return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
889327952Sdim                                               std::move(Payload));
890327952Sdim  return handleErrorImpl(std::move(Payload),
891327952Sdim                         std::forward<HandlerTs>(Handlers)...);
892327952Sdim}
893327952Sdim
894327952Sdim/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
895327952Sdim/// unhandled errors (or Errors returned by handlers) are re-concatenated and
896327952Sdim/// returned.
897327952Sdim/// Because this function returns an error, its result must also be checked
898327952Sdim/// or returned. If you intend to handle all errors use handleAllErrors
899327952Sdim/// (which returns void, and will abort() on unhandled errors) instead.
900327952Sdimtemplate <typename... HandlerTs>
901327952SdimError handleErrors(Error E, HandlerTs &&... Hs) {
902327952Sdim  if (!E)
903327952Sdim    return Error::success();
904327952Sdim
905327952Sdim  std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
906327952Sdim
907327952Sdim  if (Payload->isA<ErrorList>()) {
908327952Sdim    ErrorList &List = static_cast<ErrorList &>(*Payload);
909327952Sdim    Error R;
910327952Sdim    for (auto &P : List.Payloads)
911327952Sdim      R = ErrorList::join(
912327952Sdim          std::move(R),
913327952Sdim          handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
914327952Sdim    return R;
915327952Sdim  }
916327952Sdim
917327952Sdim  return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
918327952Sdim}
919327952Sdim
920341825Sdim/// Behaves the same as handleErrors, except that by contract all errors
921341825Sdim/// *must* be handled by the given handlers (i.e. there must be no remaining
922341825Sdim/// errors after running the handlers, or llvm_unreachable is called).
923327952Sdimtemplate <typename... HandlerTs>
924327952Sdimvoid handleAllErrors(Error E, HandlerTs &&... Handlers) {
925327952Sdim  cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
926327952Sdim}
927327952Sdim
928327952Sdim/// Check that E is a non-error, then drop it.
929341825Sdim/// If E is an error, llvm_unreachable will be called.
930327952Sdiminline void handleAllErrors(Error E) {
931327952Sdim  cantFail(std::move(E));
932327952Sdim}
933327952Sdim
934327952Sdim/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
935327952Sdim///
936327952Sdim/// If the incoming value is a success value it is returned unmodified. If it
937327952Sdim/// is a failure value then it the contained error is passed to handleErrors.
938327952Sdim/// If handleErrors is able to handle the error then the RecoveryPath functor
939327952Sdim/// is called to supply the final result. If handleErrors is not able to
940327952Sdim/// handle all errors then the unhandled errors are returned.
941327952Sdim///
942327952Sdim/// This utility enables the follow pattern:
943327952Sdim///
944327952Sdim///   @code{.cpp}
945327952Sdim///   enum FooStrategy { Aggressive, Conservative };
946327952Sdim///   Expected<Foo> foo(FooStrategy S);
947327952Sdim///
948327952Sdim///   auto ResultOrErr =
949327952Sdim///     handleExpected(
950327952Sdim///       foo(Aggressive),
951327952Sdim///       []() { return foo(Conservative); },
952327952Sdim///       [](AggressiveStrategyError&) {
953327952Sdim///         // Implicitly conusme this - we'll recover by using a conservative
954327952Sdim///         // strategy.
955327952Sdim///       });
956327952Sdim///
957327952Sdim///   @endcode
958327952Sdimtemplate <typename T, typename RecoveryFtor, typename... HandlerTs>
959327952SdimExpected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
960327952Sdim                           HandlerTs &&... Handlers) {
961327952Sdim  if (ValOrErr)
962327952Sdim    return ValOrErr;
963327952Sdim
964327952Sdim  if (auto Err = handleErrors(ValOrErr.takeError(),
965327952Sdim                              std::forward<HandlerTs>(Handlers)...))
966327952Sdim    return std::move(Err);
967327952Sdim
968327952Sdim  return RecoveryPath();
969327952Sdim}
970327952Sdim
971327952Sdim/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
972327952Sdim/// will be printed before the first one is logged. A newline will be printed
973327952Sdim/// after each error.
974327952Sdim///
975344779Sdim/// This function is compatible with the helpers from Support/WithColor.h. You
976344779Sdim/// can pass any of them as the OS. Please consider using them instead of
977344779Sdim/// including 'error: ' in the ErrorBanner.
978344779Sdim///
979327952Sdim/// This is useful in the base level of your program to allow clean termination
980327952Sdim/// (allowing clean deallocation of resources, etc.), while reporting error
981327952Sdim/// information to the user.
982344779Sdimvoid logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {});
983327952Sdim
984327952Sdim/// Write all error messages (if any) in E to a string. The newline character
985327952Sdim/// is used to separate error messages.
986327952Sdiminline std::string toString(Error E) {
987327952Sdim  SmallVector<std::string, 2> Errors;
988327952Sdim  handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
989327952Sdim    Errors.push_back(EI.message());
990327952Sdim  });
991327952Sdim  return join(Errors.begin(), Errors.end(), "\n");
992327952Sdim}
993327952Sdim
994327952Sdim/// Consume a Error without doing anything. This method should be used
995327952Sdim/// only where an error can be considered a reasonable and expected return
996327952Sdim/// value.
997327952Sdim///
998327952Sdim/// Uses of this method are potentially indicative of design problems: If it's
999327952Sdim/// legitimate to do nothing while processing an "error", the error-producer
1000327952Sdim/// might be more clearly refactored to return an Optional<T>.
1001327952Sdiminline void consumeError(Error Err) {
1002327952Sdim  handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
1003327952Sdim}
1004327952Sdim
1005360784Sdim/// Convert an Expected to an Optional without doing anything. This method
1006360784Sdim/// should be used only where an error can be considered a reasonable and
1007360784Sdim/// expected return value.
1008360784Sdim///
1009360784Sdim/// Uses of this method are potentially indicative of problems: perhaps the
1010360784Sdim/// error should be propagated further, or the error-producer should just
1011360784Sdim/// return an Optional in the first place.
1012360784Sdimtemplate <typename T> Optional<T> expectedToOptional(Expected<T> &&E) {
1013360784Sdim  if (E)
1014360784Sdim    return std::move(*E);
1015360784Sdim  consumeError(E.takeError());
1016360784Sdim  return None;
1017360784Sdim}
1018360784Sdim
1019341825Sdim/// Helper for converting an Error to a bool.
1020341825Sdim///
1021341825Sdim/// This method returns true if Err is in an error state, or false if it is
1022341825Sdim/// in a success state.  Puts Err in a checked state in both cases (unlike
1023341825Sdim/// Error::operator bool(), which only does this for success states).
1024341825Sdiminline bool errorToBool(Error Err) {
1025341825Sdim  bool IsError = static_cast<bool>(Err);
1026341825Sdim  if (IsError)
1027341825Sdim    consumeError(std::move(Err));
1028341825Sdim  return IsError;
1029341825Sdim}
1030341825Sdim
1031327952Sdim/// Helper for Errors used as out-parameters.
1032327952Sdim///
1033327952Sdim/// This helper is for use with the Error-as-out-parameter idiom, where an error
1034327952Sdim/// is passed to a function or method by reference, rather than being returned.
1035327952Sdim/// In such cases it is helpful to set the checked bit on entry to the function
1036327952Sdim/// so that the error can be written to (unchecked Errors abort on assignment)
1037327952Sdim/// and clear the checked bit on exit so that clients cannot accidentally forget
1038327952Sdim/// to check the result. This helper performs these actions automatically using
1039327952Sdim/// RAII:
1040327952Sdim///
1041327952Sdim///   @code{.cpp}
1042327952Sdim///   Result foo(Error &Err) {
1043327952Sdim///     ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1044327952Sdim///     // <body of foo>
1045327952Sdim///     // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1046327952Sdim///   }
1047327952Sdim///   @endcode
1048327952Sdim///
1049327952Sdim/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1050327952Sdim/// used with optional Errors (Error pointers that are allowed to be null). If
1051327952Sdim/// ErrorAsOutParameter took an Error reference, an instance would have to be
1052327952Sdim/// created inside every condition that verified that Error was non-null. By
1053327952Sdim/// taking an Error pointer we can just create one instance at the top of the
1054327952Sdim/// function.
1055327952Sdimclass ErrorAsOutParameter {
1056327952Sdimpublic:
1057327952Sdim  ErrorAsOutParameter(Error *Err) : Err(Err) {
1058327952Sdim    // Raise the checked bit if Err is success.
1059327952Sdim    if (Err)
1060327952Sdim      (void)!!*Err;
1061327952Sdim  }
1062327952Sdim
1063327952Sdim  ~ErrorAsOutParameter() {
1064327952Sdim    // Clear the checked bit.
1065327952Sdim    if (Err && !*Err)
1066327952Sdim      *Err = Error::success();
1067327952Sdim  }
1068327952Sdim
1069327952Sdimprivate:
1070327952Sdim  Error *Err;
1071327952Sdim};
1072327952Sdim
1073321369Sdim/// Helper for Expected<T>s used as out-parameters.
1074321369Sdim///
1075321369Sdim/// See ErrorAsOutParameter.
1076321369Sdimtemplate <typename T>
1077321369Sdimclass ExpectedAsOutParameter {
1078321369Sdimpublic:
1079321369Sdim  ExpectedAsOutParameter(Expected<T> *ValOrErr)
1080321369Sdim    : ValOrErr(ValOrErr) {
1081321369Sdim    if (ValOrErr)
1082321369Sdim      (void)!!*ValOrErr;
1083321369Sdim  }
1084321369Sdim
1085321369Sdim  ~ExpectedAsOutParameter() {
1086321369Sdim    if (ValOrErr)
1087321369Sdim      ValOrErr->setUnchecked();
1088321369Sdim  }
1089321369Sdim
1090321369Sdimprivate:
1091321369Sdim  Expected<T> *ValOrErr;
1092321369Sdim};
1093321369Sdim
1094303231Sdim/// This class wraps a std::error_code in a Error.
1095303231Sdim///
1096303231Sdim/// This is useful if you're writing an interface that returns a Error
1097303231Sdim/// (or Expected) and you want to call code that still returns
1098303231Sdim/// std::error_codes.
1099303231Sdimclass ECError : public ErrorInfo<ECError> {
1100303231Sdim  friend Error errorCodeToError(std::error_code);
1101314564Sdim
1102344779Sdim  virtual void anchor() override;
1103344779Sdim
1104303231Sdimpublic:
1105303231Sdim  void setErrorCode(std::error_code EC) { this->EC = EC; }
1106303231Sdim  std::error_code convertToErrorCode() const override { return EC; }
1107303231Sdim  void log(raw_ostream &OS) const override { OS << EC.message(); }
1108303231Sdim
1109303231Sdim  // Used by ErrorInfo::classID.
1110303231Sdim  static char ID;
1111303231Sdim
1112303231Sdimprotected:
1113303231Sdim  ECError() = default;
1114303231Sdim  ECError(std::error_code EC) : EC(EC) {}
1115314564Sdim
1116303231Sdim  std::error_code EC;
1117303231Sdim};
1118303231Sdim
1119303231Sdim/// The value returned by this function can be returned from convertToErrorCode
1120303231Sdim/// for Error values where no sensible translation to std::error_code exists.
1121303231Sdim/// It should only be used in this situation, and should never be used where a
1122303231Sdim/// sensible conversion to std::error_code is available, as attempts to convert
1123303231Sdim/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1124303231Sdim///error to try to convert such a value).
1125303231Sdimstd::error_code inconvertibleErrorCode();
1126303231Sdim
1127303231Sdim/// Helper for converting an std::error_code to a Error.
1128303231SdimError errorCodeToError(std::error_code EC);
1129303231Sdim
1130303231Sdim/// Helper for converting an ECError to a std::error_code.
1131303231Sdim///
1132303231Sdim/// This method requires that Err be Error() or an ECError, otherwise it
1133303231Sdim/// will trigger a call to abort().
1134303231Sdimstd::error_code errorToErrorCode(Error Err);
1135303231Sdim
1136303231Sdim/// Convert an ErrorOr<T> to an Expected<T>.
1137303231Sdimtemplate <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1138303231Sdim  if (auto EC = EO.getError())
1139303231Sdim    return errorCodeToError(EC);
1140303231Sdim  return std::move(*EO);
1141303231Sdim}
1142303231Sdim
1143303231Sdim/// Convert an Expected<T> to an ErrorOr<T>.
1144303231Sdimtemplate <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1145303231Sdim  if (auto Err = E.takeError())
1146303231Sdim    return errorToErrorCode(std::move(Err));
1147303231Sdim  return std::move(*E);
1148303231Sdim}
1149303231Sdim
1150303231Sdim/// This class wraps a string in an Error.
1151303231Sdim///
1152303231Sdim/// StringError is useful in cases where the client is not expected to be able
1153303231Sdim/// to consume the specific error message programmatically (for example, if the
1154303231Sdim/// error message is to be presented to the user).
1155344779Sdim///
1156344779Sdim/// StringError can also be used when additional information is to be printed
1157344779Sdim/// along with a error_code message. Depending on the constructor called, this
1158344779Sdim/// class can either display:
1159344779Sdim///    1. the error_code message (ECError behavior)
1160344779Sdim///    2. a string
1161344779Sdim///    3. the error_code message and a string
1162344779Sdim///
1163344779Sdim/// These behaviors are useful when subtyping is required; for example, when a
1164344779Sdim/// specific library needs an explicit error type. In the example below,
1165344779Sdim/// PDBError is derived from StringError:
1166344779Sdim///
1167344779Sdim///   @code{.cpp}
1168344779Sdim///   Expected<int> foo() {
1169344779Sdim///      return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1170344779Sdim///                                        "Additional information");
1171344779Sdim///   }
1172344779Sdim///   @endcode
1173344779Sdim///
1174303231Sdimclass StringError : public ErrorInfo<StringError> {
1175303231Sdimpublic:
1176303231Sdim  static char ID;
1177314564Sdim
1178344779Sdim  // Prints EC + S and converts to EC
1179344779Sdim  StringError(std::error_code EC, const Twine &S = Twine());
1180344779Sdim
1181344779Sdim  // Prints S and converts to EC
1182303231Sdim  StringError(const Twine &S, std::error_code EC);
1183314564Sdim
1184303231Sdim  void log(raw_ostream &OS) const override;
1185303231Sdim  std::error_code convertToErrorCode() const override;
1186314564Sdim
1187321369Sdim  const std::string &getMessage() const { return Msg; }
1188321369Sdim
1189303231Sdimprivate:
1190303231Sdim  std::string Msg;
1191303231Sdim  std::error_code EC;
1192344779Sdim  const bool PrintMsgOnly = false;
1193303231Sdim};
1194303231Sdim
1195341825Sdim/// Create formatted StringError object.
1196341825Sdimtemplate <typename... Ts>
1197353358Sdiminline Error createStringError(std::error_code EC, char const *Fmt,
1198353358Sdim                               const Ts &... Vals) {
1199341825Sdim  std::string Buffer;
1200341825Sdim  raw_string_ostream Stream(Buffer);
1201341825Sdim  Stream << format(Fmt, Vals...);
1202341825Sdim  return make_error<StringError>(Stream.str(), EC);
1203341825Sdim}
1204341825Sdim
1205341825SdimError createStringError(std::error_code EC, char const *Msg);
1206341825Sdim
1207360784Sdiminline Error createStringError(std::error_code EC, const Twine &S) {
1208360784Sdim  return createStringError(EC, S.str().c_str());
1209360784Sdim}
1210360784Sdim
1211353358Sdimtemplate <typename... Ts>
1212353358Sdiminline Error createStringError(std::errc EC, char const *Fmt,
1213353358Sdim                               const Ts &... Vals) {
1214353358Sdim  return createStringError(std::make_error_code(EC), Fmt, Vals...);
1215353358Sdim}
1216353358Sdim
1217344779Sdim/// This class wraps a filename and another Error.
1218344779Sdim///
1219344779Sdim/// In some cases, an error needs to live along a 'source' name, in order to
1220344779Sdim/// show more detailed information to the user.
1221344779Sdimclass FileError final : public ErrorInfo<FileError> {
1222344779Sdim
1223353358Sdim  friend Error createFileError(const Twine &, Error);
1224353358Sdim  friend Error createFileError(const Twine &, size_t, Error);
1225344779Sdim
1226344779Sdimpublic:
1227344779Sdim  void log(raw_ostream &OS) const override {
1228344779Sdim    assert(Err && !FileName.empty() && "Trying to log after takeError().");
1229344779Sdim    OS << "'" << FileName << "': ";
1230353358Sdim    if (Line.hasValue())
1231353358Sdim      OS << "line " << Line.getValue() << ": ";
1232344779Sdim    Err->log(OS);
1233344779Sdim  }
1234344779Sdim
1235360784Sdim  StringRef getFileName() { return FileName; }
1236360784Sdim
1237344779Sdim  Error takeError() { return Error(std::move(Err)); }
1238344779Sdim
1239344779Sdim  std::error_code convertToErrorCode() const override;
1240344779Sdim
1241344779Sdim  // Used by ErrorInfo::classID.
1242344779Sdim  static char ID;
1243344779Sdim
1244344779Sdimprivate:
1245353358Sdim  FileError(const Twine &F, Optional<size_t> LineNum,
1246353358Sdim            std::unique_ptr<ErrorInfoBase> E) {
1247344779Sdim    assert(E && "Cannot create FileError from Error success value.");
1248353358Sdim    assert(!F.isTriviallyEmpty() &&
1249344779Sdim           "The file name provided to FileError must not be empty.");
1250353358Sdim    FileName = F.str();
1251344779Sdim    Err = std::move(E);
1252353358Sdim    Line = std::move(LineNum);
1253344779Sdim  }
1254344779Sdim
1255353358Sdim  static Error build(const Twine &F, Optional<size_t> Line, Error E) {
1256360784Sdim    std::unique_ptr<ErrorInfoBase> Payload;
1257360784Sdim    handleAllErrors(std::move(E),
1258360784Sdim                    [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error {
1259360784Sdim                      Payload = std::move(EIB);
1260360784Sdim                      return Error::success();
1261360784Sdim                    });
1262353358Sdim    return Error(
1263360784Sdim        std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload))));
1264344779Sdim  }
1265344779Sdim
1266344779Sdim  std::string FileName;
1267353358Sdim  Optional<size_t> Line;
1268344779Sdim  std::unique_ptr<ErrorInfoBase> Err;
1269344779Sdim};
1270344779Sdim
1271344779Sdim/// Concatenate a source file path and/or name with an Error. The resulting
1272344779Sdim/// Error is unchecked.
1273353358Sdiminline Error createFileError(const Twine &F, Error E) {
1274353358Sdim  return FileError::build(F, Optional<size_t>(), std::move(E));
1275344779Sdim}
1276344779Sdim
1277353358Sdim/// Concatenate a source file path and/or name with line number and an Error.
1278353358Sdim/// The resulting Error is unchecked.
1279353358Sdiminline Error createFileError(const Twine &F, size_t Line, Error E) {
1280353358Sdim  return FileError::build(F, Optional<size_t>(Line), std::move(E));
1281353358Sdim}
1282344779Sdim
1283353358Sdim/// Concatenate a source file path and/or name with a std::error_code
1284353358Sdim/// to form an Error object.
1285353358Sdiminline Error createFileError(const Twine &F, std::error_code EC) {
1286353358Sdim  return createFileError(F, errorCodeToError(EC));
1287353358Sdim}
1288353358Sdim
1289353358Sdim/// Concatenate a source file path and/or name with line number and
1290353358Sdim/// std::error_code to form an Error object.
1291353358Sdiminline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1292353358Sdim  return createFileError(F, Line, errorCodeToError(EC));
1293353358Sdim}
1294353358Sdim
1295353358SdimError createFileError(const Twine &F, ErrorSuccess) = delete;
1296353358Sdim
1297303231Sdim/// Helper for check-and-exit error handling.
1298303231Sdim///
1299303231Sdim/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1300303231Sdim///
1301303231Sdimclass ExitOnError {
1302303231Sdimpublic:
1303303231Sdim  /// Create an error on exit helper.
1304303231Sdim  ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1305303231Sdim      : Banner(std::move(Banner)),
1306303231Sdim        GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1307303231Sdim
1308303231Sdim  /// Set the banner string for any errors caught by operator().
1309303231Sdim  void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1310303231Sdim
1311303231Sdim  /// Set the exit-code mapper function.
1312303231Sdim  void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1313303231Sdim    this->GetExitCode = std::move(GetExitCode);
1314303231Sdim  }
1315303231Sdim
1316303231Sdim  /// Check Err. If it's in a failure state log the error(s) and exit.
1317303231Sdim  void operator()(Error Err) const { checkError(std::move(Err)); }
1318303231Sdim
1319303231Sdim  /// Check E. If it's in a success state then return the contained value. If
1320303231Sdim  /// it's in a failure state log the error(s) and exit.
1321303231Sdim  template <typename T> T operator()(Expected<T> &&E) const {
1322303231Sdim    checkError(E.takeError());
1323303231Sdim    return std::move(*E);
1324303231Sdim  }
1325303231Sdim
1326303231Sdim  /// Check E. If it's in a success state then return the contained reference. If
1327303231Sdim  /// it's in a failure state log the error(s) and exit.
1328303231Sdim  template <typename T> T& operator()(Expected<T&> &&E) const {
1329303231Sdim    checkError(E.takeError());
1330303231Sdim    return *E;
1331303231Sdim  }
1332303231Sdim
1333303231Sdimprivate:
1334303231Sdim  void checkError(Error Err) const {
1335303231Sdim    if (Err) {
1336303231Sdim      int ExitCode = GetExitCode(Err);
1337303231Sdim      logAllUnhandledErrors(std::move(Err), errs(), Banner);
1338303231Sdim      exit(ExitCode);
1339303231Sdim    }
1340303231Sdim  }
1341303231Sdim
1342303231Sdim  std::string Banner;
1343303231Sdim  std::function<int(const Error &)> GetExitCode;
1344303231Sdim};
1345303231Sdim
1346344779Sdim/// Conversion from Error to LLVMErrorRef for C error bindings.
1347344779Sdiminline LLVMErrorRef wrap(Error Err) {
1348344779Sdim  return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1349344779Sdim}
1350344779Sdim
1351344779Sdim/// Conversion from LLVMErrorRef to Error for C error bindings.
1352344779Sdiminline Error unwrap(LLVMErrorRef ErrRef) {
1353344779Sdim  return Error(std::unique_ptr<ErrorInfoBase>(
1354344779Sdim      reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1355344779Sdim}
1356344779Sdim
1357314564Sdim} // end namespace llvm
1358303231Sdim
1359303231Sdim#endif // LLVM_SUPPORT_ERROR_H
1360