PageRenderTime 62ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/include/llvm/Support/Error.h

http://github.com/earl/llvm-mirror
C Header | 1351 lines | 758 code | 188 blank | 405 comment | 63 complexity | 130faedd4db314e9f4ae15265295cd21 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines an API used to report recoverable errors.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_SUPPORT_ERROR_H
  13. #define LLVM_SUPPORT_ERROR_H
  14. #include "llvm-c/Error.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/ADT/Twine.h"
  19. #include "llvm/Config/abi-breaking.h"
  20. #include "llvm/Support/AlignOf.h"
  21. #include "llvm/Support/Compiler.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/ErrorOr.h"
  25. #include "llvm/Support/Format.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm>
  28. #include <cassert>
  29. #include <cstdint>
  30. #include <cstdlib>
  31. #include <functional>
  32. #include <memory>
  33. #include <new>
  34. #include <string>
  35. #include <system_error>
  36. #include <type_traits>
  37. #include <utility>
  38. #include <vector>
  39. namespace llvm {
  40. class ErrorSuccess;
  41. /// Base class for error info classes. Do not extend this directly: Extend
  42. /// the ErrorInfo template subclass instead.
  43. class ErrorInfoBase {
  44. public:
  45. virtual ~ErrorInfoBase() = default;
  46. /// Print an error message to an output stream.
  47. virtual void log(raw_ostream &OS) const = 0;
  48. /// Return the error message as a string.
  49. virtual std::string message() const {
  50. std::string Msg;
  51. raw_string_ostream OS(Msg);
  52. log(OS);
  53. return OS.str();
  54. }
  55. /// Convert this error to a std::error_code.
  56. ///
  57. /// This is a temporary crutch to enable interaction with code still
  58. /// using std::error_code. It will be removed in the future.
  59. virtual std::error_code convertToErrorCode() const = 0;
  60. // Returns the class ID for this type.
  61. static const void *classID() { return &ID; }
  62. // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
  63. virtual const void *dynamicClassID() const = 0;
  64. // Check whether this instance is a subclass of the class identified by
  65. // ClassID.
  66. virtual bool isA(const void *const ClassID) const {
  67. return ClassID == classID();
  68. }
  69. // Check whether this instance is a subclass of ErrorInfoT.
  70. template <typename ErrorInfoT> bool isA() const {
  71. return isA(ErrorInfoT::classID());
  72. }
  73. private:
  74. virtual void anchor();
  75. static char ID;
  76. };
  77. /// Lightweight error class with error context and mandatory checking.
  78. ///
  79. /// Instances of this class wrap a ErrorInfoBase pointer. Failure states
  80. /// are represented by setting the pointer to a ErrorInfoBase subclass
  81. /// instance containing information describing the failure. Success is
  82. /// represented by a null pointer value.
  83. ///
  84. /// Instances of Error also contains a 'Checked' flag, which must be set
  85. /// before the destructor is called, otherwise the destructor will trigger a
  86. /// runtime error. This enforces at runtime the requirement that all Error
  87. /// instances be checked or returned to the caller.
  88. ///
  89. /// There are two ways to set the checked flag, depending on what state the
  90. /// Error instance is in. For Error instances indicating success, it
  91. /// is sufficient to invoke the boolean conversion operator. E.g.:
  92. ///
  93. /// @code{.cpp}
  94. /// Error foo(<...>);
  95. ///
  96. /// if (auto E = foo(<...>))
  97. /// return E; // <- Return E if it is in the error state.
  98. /// // We have verified that E was in the success state. It can now be safely
  99. /// // destroyed.
  100. /// @endcode
  101. ///
  102. /// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
  103. /// without testing the return value will raise a runtime error, even if foo
  104. /// returns success.
  105. ///
  106. /// For Error instances representing failure, you must use either the
  107. /// handleErrors or handleAllErrors function with a typed handler. E.g.:
  108. ///
  109. /// @code{.cpp}
  110. /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
  111. /// // Custom error info.
  112. /// };
  113. ///
  114. /// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
  115. ///
  116. /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
  117. /// auto NewE =
  118. /// handleErrors(E,
  119. /// [](const MyErrorInfo &M) {
  120. /// // Deal with the error.
  121. /// },
  122. /// [](std::unique_ptr<OtherError> M) -> Error {
  123. /// if (canHandle(*M)) {
  124. /// // handle error.
  125. /// return Error::success();
  126. /// }
  127. /// // Couldn't handle this error instance. Pass it up the stack.
  128. /// return Error(std::move(M));
  129. /// );
  130. /// // Note - we must check or return NewE in case any of the handlers
  131. /// // returned a new error.
  132. /// @endcode
  133. ///
  134. /// The handleAllErrors function is identical to handleErrors, except
  135. /// that it has a void return type, and requires all errors to be handled and
  136. /// no new errors be returned. It prevents errors (assuming they can all be
  137. /// handled) from having to be bubbled all the way to the top-level.
  138. ///
  139. /// *All* Error instances must be checked before destruction, even if
  140. /// they're moved-assigned or constructed from Success values that have already
  141. /// been checked. This enforces checking through all levels of the call stack.
  142. class LLVM_NODISCARD Error {
  143. // Both ErrorList and FileError need to be able to yank ErrorInfoBase
  144. // pointers out of this class to add to the error list.
  145. friend class ErrorList;
  146. friend class FileError;
  147. // handleErrors needs to be able to set the Checked flag.
  148. template <typename... HandlerTs>
  149. friend Error handleErrors(Error E, HandlerTs &&... Handlers);
  150. // Expected<T> needs to be able to steal the payload when constructed from an
  151. // error.
  152. template <typename T> friend class Expected;
  153. // wrap needs to be able to steal the payload.
  154. friend LLVMErrorRef wrap(Error);
  155. protected:
  156. /// Create a success value. Prefer using 'Error::success()' for readability
  157. Error() {
  158. setPtr(nullptr);
  159. setChecked(false);
  160. }
  161. public:
  162. /// Create a success value.
  163. static ErrorSuccess success();
  164. // Errors are not copy-constructable.
  165. Error(const Error &Other) = delete;
  166. /// Move-construct an error value. The newly constructed error is considered
  167. /// unchecked, even if the source error had been checked. The original error
  168. /// becomes a checked Success value, regardless of its original state.
  169. Error(Error &&Other) {
  170. setChecked(true);
  171. *this = std::move(Other);
  172. }
  173. /// Create an error value. Prefer using the 'make_error' function, but
  174. /// this constructor can be useful when "re-throwing" errors from handlers.
  175. Error(std::unique_ptr<ErrorInfoBase> Payload) {
  176. setPtr(Payload.release());
  177. setChecked(false);
  178. }
  179. // Errors are not copy-assignable.
  180. Error &operator=(const Error &Other) = delete;
  181. /// Move-assign an error value. The current error must represent success, you
  182. /// you cannot overwrite an unhandled error. The current error is then
  183. /// considered unchecked. The source error becomes a checked success value,
  184. /// regardless of its original state.
  185. Error &operator=(Error &&Other) {
  186. // Don't allow overwriting of unchecked values.
  187. assertIsChecked();
  188. setPtr(Other.getPtr());
  189. // This Error is unchecked, even if the source error was checked.
  190. setChecked(false);
  191. // Null out Other's payload and set its checked bit.
  192. Other.setPtr(nullptr);
  193. Other.setChecked(true);
  194. return *this;
  195. }
  196. /// Destroy a Error. Fails with a call to abort() if the error is
  197. /// unchecked.
  198. ~Error() {
  199. assertIsChecked();
  200. delete getPtr();
  201. }
  202. /// Bool conversion. Returns true if this Error is in a failure state,
  203. /// and false if it is in an accept state. If the error is in a Success state
  204. /// it will be considered checked.
  205. explicit operator bool() {
  206. setChecked(getPtr() == nullptr);
  207. return getPtr() != nullptr;
  208. }
  209. /// Check whether one error is a subclass of another.
  210. template <typename ErrT> bool isA() const {
  211. return getPtr() && getPtr()->isA(ErrT::classID());
  212. }
  213. /// Returns the dynamic class id of this error, or null if this is a success
  214. /// value.
  215. const void* dynamicClassID() const {
  216. if (!getPtr())
  217. return nullptr;
  218. return getPtr()->dynamicClassID();
  219. }
  220. private:
  221. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  222. // assertIsChecked() happens very frequently, but under normal circumstances
  223. // is supposed to be a no-op. So we want it to be inlined, but having a bunch
  224. // of debug prints can cause the function to be too large for inlining. So
  225. // it's important that we define this function out of line so that it can't be
  226. // inlined.
  227. LLVM_ATTRIBUTE_NORETURN
  228. void fatalUncheckedError() const;
  229. #endif
  230. void assertIsChecked() {
  231. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  232. if (LLVM_UNLIKELY(!getChecked() || getPtr()))
  233. fatalUncheckedError();
  234. #endif
  235. }
  236. ErrorInfoBase *getPtr() const {
  237. return reinterpret_cast<ErrorInfoBase*>(
  238. reinterpret_cast<uintptr_t>(Payload) &
  239. ~static_cast<uintptr_t>(0x1));
  240. }
  241. void setPtr(ErrorInfoBase *EI) {
  242. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  243. Payload = reinterpret_cast<ErrorInfoBase*>(
  244. (reinterpret_cast<uintptr_t>(EI) &
  245. ~static_cast<uintptr_t>(0x1)) |
  246. (reinterpret_cast<uintptr_t>(Payload) & 0x1));
  247. #else
  248. Payload = EI;
  249. #endif
  250. }
  251. bool getChecked() const {
  252. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  253. return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
  254. #else
  255. return true;
  256. #endif
  257. }
  258. void setChecked(bool V) {
  259. Payload = reinterpret_cast<ErrorInfoBase*>(
  260. (reinterpret_cast<uintptr_t>(Payload) &
  261. ~static_cast<uintptr_t>(0x1)) |
  262. (V ? 0 : 1));
  263. }
  264. std::unique_ptr<ErrorInfoBase> takePayload() {
  265. std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
  266. setPtr(nullptr);
  267. setChecked(true);
  268. return Tmp;
  269. }
  270. friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
  271. if (auto P = E.getPtr())
  272. P->log(OS);
  273. else
  274. OS << "success";
  275. return OS;
  276. }
  277. ErrorInfoBase *Payload = nullptr;
  278. };
  279. /// Subclass of Error for the sole purpose of identifying the success path in
  280. /// the type system. This allows to catch invalid conversion to Expected<T> at
  281. /// compile time.
  282. class ErrorSuccess final : public Error {};
  283. inline ErrorSuccess Error::success() { return ErrorSuccess(); }
  284. /// Make a Error instance representing failure using the given error info
  285. /// type.
  286. template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
  287. return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
  288. }
  289. /// Base class for user error types. Users should declare their error types
  290. /// like:
  291. ///
  292. /// class MyError : public ErrorInfo<MyError> {
  293. /// ....
  294. /// };
  295. ///
  296. /// This class provides an implementation of the ErrorInfoBase::kind
  297. /// method, which is used by the Error RTTI system.
  298. template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
  299. class ErrorInfo : public ParentErrT {
  300. public:
  301. using ParentErrT::ParentErrT; // inherit constructors
  302. static const void *classID() { return &ThisErrT::ID; }
  303. const void *dynamicClassID() const override { return &ThisErrT::ID; }
  304. bool isA(const void *const ClassID) const override {
  305. return ClassID == classID() || ParentErrT::isA(ClassID);
  306. }
  307. };
  308. /// Special ErrorInfo subclass representing a list of ErrorInfos.
  309. /// Instances of this class are constructed by joinError.
  310. class ErrorList final : public ErrorInfo<ErrorList> {
  311. // handleErrors needs to be able to iterate the payload list of an
  312. // ErrorList.
  313. template <typename... HandlerTs>
  314. friend Error handleErrors(Error E, HandlerTs &&... Handlers);
  315. // joinErrors is implemented in terms of join.
  316. friend Error joinErrors(Error, Error);
  317. public:
  318. void log(raw_ostream &OS) const override {
  319. OS << "Multiple errors:\n";
  320. for (auto &ErrPayload : Payloads) {
  321. ErrPayload->log(OS);
  322. OS << "\n";
  323. }
  324. }
  325. std::error_code convertToErrorCode() const override;
  326. // Used by ErrorInfo::classID.
  327. static char ID;
  328. private:
  329. ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
  330. std::unique_ptr<ErrorInfoBase> Payload2) {
  331. assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
  332. "ErrorList constructor payloads should be singleton errors");
  333. Payloads.push_back(std::move(Payload1));
  334. Payloads.push_back(std::move(Payload2));
  335. }
  336. static Error join(Error E1, Error E2) {
  337. if (!E1)
  338. return E2;
  339. if (!E2)
  340. return E1;
  341. if (E1.isA<ErrorList>()) {
  342. auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
  343. if (E2.isA<ErrorList>()) {
  344. auto E2Payload = E2.takePayload();
  345. auto &E2List = static_cast<ErrorList &>(*E2Payload);
  346. for (auto &Payload : E2List.Payloads)
  347. E1List.Payloads.push_back(std::move(Payload));
  348. } else
  349. E1List.Payloads.push_back(E2.takePayload());
  350. return E1;
  351. }
  352. if (E2.isA<ErrorList>()) {
  353. auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
  354. E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
  355. return E2;
  356. }
  357. return Error(std::unique_ptr<ErrorList>(
  358. new ErrorList(E1.takePayload(), E2.takePayload())));
  359. }
  360. std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
  361. };
  362. /// Concatenate errors. The resulting Error is unchecked, and contains the
  363. /// ErrorInfo(s), if any, contained in E1, followed by the
  364. /// ErrorInfo(s), if any, contained in E2.
  365. inline Error joinErrors(Error E1, Error E2) {
  366. return ErrorList::join(std::move(E1), std::move(E2));
  367. }
  368. /// Tagged union holding either a T or a Error.
  369. ///
  370. /// This class parallels ErrorOr, but replaces error_code with Error. Since
  371. /// Error cannot be copied, this class replaces getError() with
  372. /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
  373. /// error class type.
  374. template <class T> class LLVM_NODISCARD Expected {
  375. template <class T1> friend class ExpectedAsOutParameter;
  376. template <class OtherT> friend class Expected;
  377. static const bool isRef = std::is_reference<T>::value;
  378. using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
  379. using error_type = std::unique_ptr<ErrorInfoBase>;
  380. public:
  381. using storage_type = typename std::conditional<isRef, wrap, T>::type;
  382. using value_type = T;
  383. private:
  384. using reference = typename std::remove_reference<T>::type &;
  385. using const_reference = const typename std::remove_reference<T>::type &;
  386. using pointer = typename std::remove_reference<T>::type *;
  387. using const_pointer = const typename std::remove_reference<T>::type *;
  388. public:
  389. /// Create an Expected<T> error value from the given Error.
  390. Expected(Error Err)
  391. : HasError(true)
  392. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  393. // Expected is unchecked upon construction in Debug builds.
  394. , Unchecked(true)
  395. #endif
  396. {
  397. assert(Err && "Cannot create Expected<T> from Error success value.");
  398. new (getErrorStorage()) error_type(Err.takePayload());
  399. }
  400. /// Forbid to convert from Error::success() implicitly, this avoids having
  401. /// Expected<T> foo() { return Error::success(); } which compiles otherwise
  402. /// but triggers the assertion above.
  403. Expected(ErrorSuccess) = delete;
  404. /// Create an Expected<T> success value from the given OtherT value, which
  405. /// must be convertible to T.
  406. template <typename OtherT>
  407. Expected(OtherT &&Val,
  408. typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
  409. * = nullptr)
  410. : HasError(false)
  411. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  412. // Expected is unchecked upon construction in Debug builds.
  413. , Unchecked(true)
  414. #endif
  415. {
  416. new (getStorage()) storage_type(std::forward<OtherT>(Val));
  417. }
  418. /// Move construct an Expected<T> value.
  419. Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
  420. /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
  421. /// must be convertible to T.
  422. template <class OtherT>
  423. Expected(Expected<OtherT> &&Other,
  424. typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
  425. * = nullptr) {
  426. moveConstruct(std::move(Other));
  427. }
  428. /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
  429. /// isn't convertible to T.
  430. template <class OtherT>
  431. explicit Expected(
  432. Expected<OtherT> &&Other,
  433. typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
  434. nullptr) {
  435. moveConstruct(std::move(Other));
  436. }
  437. /// Move-assign from another Expected<T>.
  438. Expected &operator=(Expected &&Other) {
  439. moveAssign(std::move(Other));
  440. return *this;
  441. }
  442. /// Destroy an Expected<T>.
  443. ~Expected() {
  444. assertIsChecked();
  445. if (!HasError)
  446. getStorage()->~storage_type();
  447. else
  448. getErrorStorage()->~error_type();
  449. }
  450. /// Return false if there is an error.
  451. explicit operator bool() {
  452. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  453. Unchecked = HasError;
  454. #endif
  455. return !HasError;
  456. }
  457. /// Returns a reference to the stored T value.
  458. reference get() {
  459. assertIsChecked();
  460. return *getStorage();
  461. }
  462. /// Returns a const reference to the stored T value.
  463. const_reference get() const {
  464. assertIsChecked();
  465. return const_cast<Expected<T> *>(this)->get();
  466. }
  467. /// Check that this Expected<T> is an error of type ErrT.
  468. template <typename ErrT> bool errorIsA() const {
  469. return HasError && (*getErrorStorage())->template isA<ErrT>();
  470. }
  471. /// Take ownership of the stored error.
  472. /// After calling this the Expected<T> is in an indeterminate state that can
  473. /// only be safely destructed. No further calls (beside the destructor) should
  474. /// be made on the Expected<T> value.
  475. Error takeError() {
  476. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  477. Unchecked = false;
  478. #endif
  479. return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
  480. }
  481. /// Returns a pointer to the stored T value.
  482. pointer operator->() {
  483. assertIsChecked();
  484. return toPointer(getStorage());
  485. }
  486. /// Returns a const pointer to the stored T value.
  487. const_pointer operator->() const {
  488. assertIsChecked();
  489. return toPointer(getStorage());
  490. }
  491. /// Returns a reference to the stored T value.
  492. reference operator*() {
  493. assertIsChecked();
  494. return *getStorage();
  495. }
  496. /// Returns a const reference to the stored T value.
  497. const_reference operator*() const {
  498. assertIsChecked();
  499. return *getStorage();
  500. }
  501. private:
  502. template <class T1>
  503. static bool compareThisIfSameType(const T1 &a, const T1 &b) {
  504. return &a == &b;
  505. }
  506. template <class T1, class T2>
  507. static bool compareThisIfSameType(const T1 &a, const T2 &b) {
  508. return false;
  509. }
  510. template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
  511. HasError = Other.HasError;
  512. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  513. Unchecked = true;
  514. Other.Unchecked = false;
  515. #endif
  516. if (!HasError)
  517. new (getStorage()) storage_type(std::move(*Other.getStorage()));
  518. else
  519. new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
  520. }
  521. template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
  522. assertIsChecked();
  523. if (compareThisIfSameType(*this, Other))
  524. return;
  525. this->~Expected();
  526. new (this) Expected(std::move(Other));
  527. }
  528. pointer toPointer(pointer Val) { return Val; }
  529. const_pointer toPointer(const_pointer Val) const { return Val; }
  530. pointer toPointer(wrap *Val) { return &Val->get(); }
  531. const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
  532. storage_type *getStorage() {
  533. assert(!HasError && "Cannot get value when an error exists!");
  534. return reinterpret_cast<storage_type *>(TStorage.buffer);
  535. }
  536. const storage_type *getStorage() const {
  537. assert(!HasError && "Cannot get value when an error exists!");
  538. return reinterpret_cast<const storage_type *>(TStorage.buffer);
  539. }
  540. error_type *getErrorStorage() {
  541. assert(HasError && "Cannot get error when a value exists!");
  542. return reinterpret_cast<error_type *>(ErrorStorage.buffer);
  543. }
  544. const error_type *getErrorStorage() const {
  545. assert(HasError && "Cannot get error when a value exists!");
  546. return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
  547. }
  548. // Used by ExpectedAsOutParameter to reset the checked flag.
  549. void setUnchecked() {
  550. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  551. Unchecked = true;
  552. #endif
  553. }
  554. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  555. LLVM_ATTRIBUTE_NORETURN
  556. LLVM_ATTRIBUTE_NOINLINE
  557. void fatalUncheckedExpected() const {
  558. dbgs() << "Expected<T> must be checked before access or destruction.\n";
  559. if (HasError) {
  560. dbgs() << "Unchecked Expected<T> contained error:\n";
  561. (*getErrorStorage())->log(dbgs());
  562. } else
  563. dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
  564. "values in success mode must still be checked prior to being "
  565. "destroyed).\n";
  566. abort();
  567. }
  568. #endif
  569. void assertIsChecked() {
  570. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  571. if (LLVM_UNLIKELY(Unchecked))
  572. fatalUncheckedExpected();
  573. #endif
  574. }
  575. union {
  576. AlignedCharArrayUnion<storage_type> TStorage;
  577. AlignedCharArrayUnion<error_type> ErrorStorage;
  578. };
  579. bool HasError : 1;
  580. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  581. bool Unchecked : 1;
  582. #endif
  583. };
  584. /// Report a serious error, calling any installed error handler. See
  585. /// ErrorHandling.h.
  586. LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err,
  587. bool gen_crash_diag = true);
  588. /// Report a fatal error if Err is a failure value.
  589. ///
  590. /// This function can be used to wrap calls to fallible functions ONLY when it
  591. /// is known that the Error will always be a success value. E.g.
  592. ///
  593. /// @code{.cpp}
  594. /// // foo only attempts the fallible operation if DoFallibleOperation is
  595. /// // true. If DoFallibleOperation is false then foo always returns
  596. /// // Error::success().
  597. /// Error foo(bool DoFallibleOperation);
  598. ///
  599. /// cantFail(foo(false));
  600. /// @endcode
  601. inline void cantFail(Error Err, const char *Msg = nullptr) {
  602. if (Err) {
  603. if (!Msg)
  604. Msg = "Failure value returned from cantFail wrapped call";
  605. #ifndef NDEBUG
  606. std::string Str;
  607. raw_string_ostream OS(Str);
  608. OS << Msg << "\n" << Err;
  609. Msg = OS.str().c_str();
  610. #endif
  611. llvm_unreachable(Msg);
  612. }
  613. }
  614. /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
  615. /// returns the contained value.
  616. ///
  617. /// This function can be used to wrap calls to fallible functions ONLY when it
  618. /// is known that the Error will always be a success value. E.g.
  619. ///
  620. /// @code{.cpp}
  621. /// // foo only attempts the fallible operation if DoFallibleOperation is
  622. /// // true. If DoFallibleOperation is false then foo always returns an int.
  623. /// Expected<int> foo(bool DoFallibleOperation);
  624. ///
  625. /// int X = cantFail(foo(false));
  626. /// @endcode
  627. template <typename T>
  628. T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
  629. if (ValOrErr)
  630. return std::move(*ValOrErr);
  631. else {
  632. if (!Msg)
  633. Msg = "Failure value returned from cantFail wrapped call";
  634. #ifndef NDEBUG
  635. std::string Str;
  636. raw_string_ostream OS(Str);
  637. auto E = ValOrErr.takeError();
  638. OS << Msg << "\n" << E;
  639. Msg = OS.str().c_str();
  640. #endif
  641. llvm_unreachable(Msg);
  642. }
  643. }
  644. /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
  645. /// returns the contained reference.
  646. ///
  647. /// This function can be used to wrap calls to fallible functions ONLY when it
  648. /// is known that the Error will always be a success value. E.g.
  649. ///
  650. /// @code{.cpp}
  651. /// // foo only attempts the fallible operation if DoFallibleOperation is
  652. /// // true. If DoFallibleOperation is false then foo always returns a Bar&.
  653. /// Expected<Bar&> foo(bool DoFallibleOperation);
  654. ///
  655. /// Bar &X = cantFail(foo(false));
  656. /// @endcode
  657. template <typename T>
  658. T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
  659. if (ValOrErr)
  660. return *ValOrErr;
  661. else {
  662. if (!Msg)
  663. Msg = "Failure value returned from cantFail wrapped call";
  664. #ifndef NDEBUG
  665. std::string Str;
  666. raw_string_ostream OS(Str);
  667. auto E = ValOrErr.takeError();
  668. OS << Msg << "\n" << E;
  669. Msg = OS.str().c_str();
  670. #endif
  671. llvm_unreachable(Msg);
  672. }
  673. }
  674. /// Helper for testing applicability of, and applying, handlers for
  675. /// ErrorInfo types.
  676. template <typename HandlerT>
  677. class ErrorHandlerTraits
  678. : public ErrorHandlerTraits<decltype(
  679. &std::remove_reference<HandlerT>::type::operator())> {};
  680. // Specialization functions of the form 'Error (const ErrT&)'.
  681. template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
  682. public:
  683. static bool appliesTo(const ErrorInfoBase &E) {
  684. return E.template isA<ErrT>();
  685. }
  686. template <typename HandlerT>
  687. static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
  688. assert(appliesTo(*E) && "Applying incorrect handler");
  689. return H(static_cast<ErrT &>(*E));
  690. }
  691. };
  692. // Specialization functions of the form 'void (const ErrT&)'.
  693. template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
  694. public:
  695. static bool appliesTo(const ErrorInfoBase &E) {
  696. return E.template isA<ErrT>();
  697. }
  698. template <typename HandlerT>
  699. static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
  700. assert(appliesTo(*E) && "Applying incorrect handler");
  701. H(static_cast<ErrT &>(*E));
  702. return Error::success();
  703. }
  704. };
  705. /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
  706. template <typename ErrT>
  707. class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
  708. public:
  709. static bool appliesTo(const ErrorInfoBase &E) {
  710. return E.template isA<ErrT>();
  711. }
  712. template <typename HandlerT>
  713. static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
  714. assert(appliesTo(*E) && "Applying incorrect handler");
  715. std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
  716. return H(std::move(SubE));
  717. }
  718. };
  719. /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
  720. template <typename ErrT>
  721. class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
  722. public:
  723. static bool appliesTo(const ErrorInfoBase &E) {
  724. return E.template isA<ErrT>();
  725. }
  726. template <typename HandlerT>
  727. static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
  728. assert(appliesTo(*E) && "Applying incorrect handler");
  729. std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
  730. H(std::move(SubE));
  731. return Error::success();
  732. }
  733. };
  734. // Specialization for member functions of the form 'RetT (const ErrT&)'.
  735. template <typename C, typename RetT, typename ErrT>
  736. class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
  737. : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
  738. // Specialization for member functions of the form 'RetT (const ErrT&) const'.
  739. template <typename C, typename RetT, typename ErrT>
  740. class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
  741. : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
  742. // Specialization for member functions of the form 'RetT (const ErrT&)'.
  743. template <typename C, typename RetT, typename ErrT>
  744. class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
  745. : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
  746. // Specialization for member functions of the form 'RetT (const ErrT&) const'.
  747. template <typename C, typename RetT, typename ErrT>
  748. class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
  749. : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
  750. /// Specialization for member functions of the form
  751. /// 'RetT (std::unique_ptr<ErrT>)'.
  752. template <typename C, typename RetT, typename ErrT>
  753. class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
  754. : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
  755. /// Specialization for member functions of the form
  756. /// 'RetT (std::unique_ptr<ErrT>) const'.
  757. template <typename C, typename RetT, typename ErrT>
  758. class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
  759. : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
  760. inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
  761. return Error(std::move(Payload));
  762. }
  763. template <typename HandlerT, typename... HandlerTs>
  764. Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
  765. HandlerT &&Handler, HandlerTs &&... Handlers) {
  766. if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
  767. return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
  768. std::move(Payload));
  769. return handleErrorImpl(std::move(Payload),
  770. std::forward<HandlerTs>(Handlers)...);
  771. }
  772. /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
  773. /// unhandled errors (or Errors returned by handlers) are re-concatenated and
  774. /// returned.
  775. /// Because this function returns an error, its result must also be checked
  776. /// or returned. If you intend to handle all errors use handleAllErrors
  777. /// (which returns void, and will abort() on unhandled errors) instead.
  778. template <typename... HandlerTs>
  779. Error handleErrors(Error E, HandlerTs &&... Hs) {
  780. if (!E)
  781. return Error::success();
  782. std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
  783. if (Payload->isA<ErrorList>()) {
  784. ErrorList &List = static_cast<ErrorList &>(*Payload);
  785. Error R;
  786. for (auto &P : List.Payloads)
  787. R = ErrorList::join(
  788. std::move(R),
  789. handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
  790. return R;
  791. }
  792. return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
  793. }
  794. /// Behaves the same as handleErrors, except that by contract all errors
  795. /// *must* be handled by the given handlers (i.e. there must be no remaining
  796. /// errors after running the handlers, or llvm_unreachable is called).
  797. template <typename... HandlerTs>
  798. void handleAllErrors(Error E, HandlerTs &&... Handlers) {
  799. cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
  800. }
  801. /// Check that E is a non-error, then drop it.
  802. /// If E is an error, llvm_unreachable will be called.
  803. inline void handleAllErrors(Error E) {
  804. cantFail(std::move(E));
  805. }
  806. /// Handle any errors (if present) in an Expected<T>, then try a recovery path.
  807. ///
  808. /// If the incoming value is a success value it is returned unmodified. If it
  809. /// is a failure value then it the contained error is passed to handleErrors.
  810. /// If handleErrors is able to handle the error then the RecoveryPath functor
  811. /// is called to supply the final result. If handleErrors is not able to
  812. /// handle all errors then the unhandled errors are returned.
  813. ///
  814. /// This utility enables the follow pattern:
  815. ///
  816. /// @code{.cpp}
  817. /// enum FooStrategy { Aggressive, Conservative };
  818. /// Expected<Foo> foo(FooStrategy S);
  819. ///
  820. /// auto ResultOrErr =
  821. /// handleExpected(
  822. /// foo(Aggressive),
  823. /// []() { return foo(Conservative); },
  824. /// [](AggressiveStrategyError&) {
  825. /// // Implicitly conusme this - we'll recover by using a conservative
  826. /// // strategy.
  827. /// });
  828. ///
  829. /// @endcode
  830. template <typename T, typename RecoveryFtor, typename... HandlerTs>
  831. Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
  832. HandlerTs &&... Handlers) {
  833. if (ValOrErr)
  834. return ValOrErr;
  835. if (auto Err = handleErrors(ValOrErr.takeError(),
  836. std::forward<HandlerTs>(Handlers)...))
  837. return std::move(Err);
  838. return RecoveryPath();
  839. }
  840. /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
  841. /// will be printed before the first one is logged. A newline will be printed
  842. /// after each error.
  843. ///
  844. /// This function is compatible with the helpers from Support/WithColor.h. You
  845. /// can pass any of them as the OS. Please consider using them instead of
  846. /// including 'error: ' in the ErrorBanner.
  847. ///
  848. /// This is useful in the base level of your program to allow clean termination
  849. /// (allowing clean deallocation of resources, etc.), while reporting error
  850. /// information to the user.
  851. void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {});
  852. /// Write all error messages (if any) in E to a string. The newline character
  853. /// is used to separate error messages.
  854. inline std::string toString(Error E) {
  855. SmallVector<std::string, 2> Errors;
  856. handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
  857. Errors.push_back(EI.message());
  858. });
  859. return join(Errors.begin(), Errors.end(), "\n");
  860. }
  861. /// Consume a Error without doing anything. This method should be used
  862. /// only where an error can be considered a reasonable and expected return
  863. /// value.
  864. ///
  865. /// Uses of this method are potentially indicative of design problems: If it's
  866. /// legitimate to do nothing while processing an "error", the error-producer
  867. /// might be more clearly refactored to return an Optional<T>.
  868. inline void consumeError(Error Err) {
  869. handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
  870. }
  871. /// Convert an Expected to an Optional without doing anything. This method
  872. /// should be used only where an error can be considered a reasonable and
  873. /// expected return value.
  874. ///
  875. /// Uses of this method are potentially indicative of problems: perhaps the
  876. /// error should be propagated further, or the error-producer should just
  877. /// return an Optional in the first place.
  878. template <typename T> Optional<T> expectedToOptional(Expected<T> &&E) {
  879. if (E)
  880. return std::move(*E);
  881. consumeError(E.takeError());
  882. return None;
  883. }
  884. /// Helper for converting an Error to a bool.
  885. ///
  886. /// This method returns true if Err is in an error state, or false if it is
  887. /// in a success state. Puts Err in a checked state in both cases (unlike
  888. /// Error::operator bool(), which only does this for success states).
  889. inline bool errorToBool(Error Err) {
  890. bool IsError = static_cast<bool>(Err);
  891. if (IsError)
  892. consumeError(std::move(Err));
  893. return IsError;
  894. }
  895. /// Helper for Errors used as out-parameters.
  896. ///
  897. /// This helper is for use with the Error-as-out-parameter idiom, where an error
  898. /// is passed to a function or method by reference, rather than being returned.
  899. /// In such cases it is helpful to set the checked bit on entry to the function
  900. /// so that the error can be written to (unchecked Errors abort on assignment)
  901. /// and clear the checked bit on exit so that clients cannot accidentally forget
  902. /// to check the result. This helper performs these actions automatically using
  903. /// RAII:
  904. ///
  905. /// @code{.cpp}
  906. /// Result foo(Error &Err) {
  907. /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
  908. /// // <body of foo>
  909. /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
  910. /// }
  911. /// @endcode
  912. ///
  913. /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
  914. /// used with optional Errors (Error pointers that are allowed to be null). If
  915. /// ErrorAsOutParameter took an Error reference, an instance would have to be
  916. /// created inside every condition that verified that Error was non-null. By
  917. /// taking an Error pointer we can just create one instance at the top of the
  918. /// function.
  919. class ErrorAsOutParameter {
  920. public:
  921. ErrorAsOutParameter(Error *Err) : Err(Err) {
  922. // Raise the checked bit if Err is success.
  923. if (Err)
  924. (void)!!*Err;
  925. }
  926. ~ErrorAsOutParameter() {
  927. // Clear the checked bit.
  928. if (Err && !*Err)
  929. *Err = Error::success();
  930. }
  931. private:
  932. Error *Err;
  933. };
  934. /// Helper for Expected<T>s used as out-parameters.
  935. ///
  936. /// See ErrorAsOutParameter.
  937. template <typename T>
  938. class ExpectedAsOutParameter {
  939. public:
  940. ExpectedAsOutParameter(Expected<T> *ValOrErr)
  941. : ValOrErr(ValOrErr) {
  942. if (ValOrErr)
  943. (void)!!*ValOrErr;
  944. }
  945. ~ExpectedAsOutParameter() {
  946. if (ValOrErr)
  947. ValOrErr->setUnchecked();
  948. }
  949. private:
  950. Expected<T> *ValOrErr;
  951. };
  952. /// This class wraps a std::error_code in a Error.
  953. ///
  954. /// This is useful if you're writing an interface that returns a Error
  955. /// (or Expected) and you want to call code that still returns
  956. /// std::error_codes.
  957. class ECError : public ErrorInfo<ECError> {
  958. friend Error errorCodeToError(std::error_code);
  959. virtual void anchor() override;
  960. public:
  961. void setErrorCode(std::error_code EC) { this->EC = EC; }
  962. std::error_code convertToErrorCode() const override { return EC; }
  963. void log(raw_ostream &OS) const override { OS << EC.message(); }
  964. // Used by ErrorInfo::classID.
  965. static char ID;
  966. protected:
  967. ECError() = default;
  968. ECError(std::error_code EC) : EC(EC) {}
  969. std::error_code EC;
  970. };
  971. /// The value returned by this function can be returned from convertToErrorCode
  972. /// for Error values where no sensible translation to std::error_code exists.
  973. /// It should only be used in this situation, and should never be used where a
  974. /// sensible conversion to std::error_code is available, as attempts to convert
  975. /// to/from this error will result in a fatal error. (i.e. it is a programmatic
  976. ///error to try to convert such a value).
  977. std::error_code inconvertibleErrorCode();
  978. /// Helper for converting an std::error_code to a Error.
  979. Error errorCodeToError(std::error_code EC);
  980. /// Helper for converting an ECError to a std::error_code.
  981. ///
  982. /// This method requires that Err be Error() or an ECError, otherwise it
  983. /// will trigger a call to abort().
  984. std::error_code errorToErrorCode(Error Err);
  985. /// Convert an ErrorOr<T> to an Expected<T>.
  986. template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
  987. if (auto EC = EO.getError())
  988. return errorCodeToError(EC);
  989. return std::move(*EO);
  990. }
  991. /// Convert an Expected<T> to an ErrorOr<T>.
  992. template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
  993. if (auto Err = E.takeError())
  994. return errorToErrorCode(std::move(Err));
  995. return std::move(*E);
  996. }
  997. /// This class wraps a string in an Error.
  998. ///
  999. /// StringError is useful in cases where the client is not expected to be able
  1000. /// to consume the specific error message programmatically (for example, if the
  1001. /// error message is to be presented to the user).
  1002. ///
  1003. /// StringError can also be used when additional information is to be printed
  1004. /// along with a error_code message. Depending on the constructor called, this
  1005. /// class can either display:
  1006. /// 1. the error_code message (ECError behavior)
  1007. /// 2. a string
  1008. /// 3. the error_code message and a string
  1009. ///
  1010. /// These behaviors are useful when subtyping is required; for example, when a
  1011. /// specific library needs an explicit error type. In the example below,
  1012. /// PDBError is derived from StringError:
  1013. ///
  1014. /// @code{.cpp}
  1015. /// Expected<int> foo() {
  1016. /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
  1017. /// "Additional information");
  1018. /// }
  1019. /// @endcode
  1020. ///
  1021. class StringError : public ErrorInfo<StringError> {
  1022. public:
  1023. static char ID;
  1024. // Prints EC + S and converts to EC
  1025. StringError(std::error_code EC, const Twine &S = Twine());
  1026. // Prints S and converts to EC
  1027. StringError(const Twine &S, std::error_code EC);
  1028. void log(raw_ostream &OS) const override;
  1029. std::error_code convertToErrorCode() const override;
  1030. const std::string &getMessage() const { return Msg; }
  1031. private:
  1032. std::string Msg;
  1033. std::error_code EC;
  1034. const bool PrintMsgOnly = false;
  1035. };
  1036. /// Create formatted StringError object.
  1037. template <typename... Ts>
  1038. inline Error createStringError(std::error_code EC, char const *Fmt,
  1039. const Ts &... Vals) {
  1040. std::string Buffer;
  1041. raw_string_ostream Stream(Buffer);
  1042. Stream << format(Fmt, Vals...);
  1043. return make_error<StringError>(Stream.str(), EC);
  1044. }
  1045. Error createStringError(std::error_code EC, char const *Msg);
  1046. inline Error createStringError(std::error_code EC, const Twine &S) {
  1047. return createStringError(EC, S.str().c_str());
  1048. }
  1049. template <typename... Ts>
  1050. inline Error createStringError(std::errc EC, char const *Fmt,
  1051. const Ts &... Vals) {
  1052. return createStringError(std::make_error_code(EC), Fmt, Vals...);
  1053. }
  1054. /// This class wraps a filename and another Error.
  1055. ///
  1056. /// In some cases, an error needs to live along a 'source' name, in order to
  1057. /// show more detailed information to the user.
  1058. class FileError final : public ErrorInfo<FileError> {
  1059. friend Error createFileError(const Twine &, Error);
  1060. friend Error createFileError(const Twine &, size_t, Error);
  1061. public:
  1062. void log(raw_ostream &OS) const override {
  1063. assert(Err && !FileName.empty() && "Trying to log after takeError().");
  1064. OS << "'" << FileName << "': ";
  1065. if (Line.hasValue())
  1066. OS << "line " << Line.getValue() << ": ";
  1067. Err->log(OS);
  1068. }
  1069. Error takeError() { return Error(std::move(Err)); }
  1070. std::error_code convertToErrorCode() const override;
  1071. // Used by ErrorInfo::classID.
  1072. static char ID;
  1073. private:
  1074. FileError(const Twine &F, Optional<size_t> LineNum,
  1075. std::unique_ptr<ErrorInfoBase> E) {
  1076. assert(E && "Cannot create FileError from Error success value.");
  1077. assert(!F.isTriviallyEmpty() &&
  1078. "The file name provided to FileError must not be empty.");
  1079. FileName = F.str();
  1080. Err = std::move(E);
  1081. Line = std::move(LineNum);
  1082. }
  1083. static Error build(const Twine &F, Optional<size_t> Line, Error E) {
  1084. return Error(
  1085. std::unique_ptr<FileError>(new FileError(F, Line, E.takePayload())));
  1086. }
  1087. std::string FileName;
  1088. Optional<size_t> Line;
  1089. std::unique_ptr<ErrorInfoBase> Err;
  1090. };
  1091. /// Concatenate a source file path and/or name with an Error. The resulting
  1092. /// Error is unchecked.
  1093. inline Error createFileError(const Twine &F, Error E) {
  1094. return FileError::build(F, Optional<size_t>(), std::move(E));
  1095. }
  1096. /// Concatenate a source file path and/or name with line number and an Error.
  1097. /// The resulting Error is unchecked.
  1098. inline Error createFileError(const Twine &F, size_t Line, Error E) {
  1099. return FileError::build(F, Optional<size_t>(Line), std::move(E));
  1100. }
  1101. /// Concatenate a source file path and/or name with a std::error_code
  1102. /// to form an Error object.
  1103. inline Error createFileError(const Twine &F, std::error_code EC) {
  1104. return createFileError(F, errorCodeToError(EC));
  1105. }
  1106. /// Concatenate a source file path and/or name with line number and
  1107. /// std::error_code to form an Error object.
  1108. inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
  1109. return createFileError(F, Line, errorCodeToError(EC));
  1110. }
  1111. Error createFileError(const Twine &F, ErrorSuccess) = delete;
  1112. /// Helper for check-and-exit error handling.
  1113. ///
  1114. /// For tool use only. NOT FOR USE IN LIBRARY CODE.
  1115. ///
  1116. class ExitOnError {
  1117. public:
  1118. /// Create an error on exit helper.
  1119. ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
  1120. : Banner(std::move(Banner)),
  1121. GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
  1122. /// Set the banner string for any errors caught by operator().
  1123. void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
  1124. /// Set the exit-code mapper function.
  1125. void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
  1126. this->GetExitCode = std::move(GetExitCode);
  1127. }
  1128. /// Check Err. If it's in a failure state log the error(s) and exit.
  1129. void operator()(Error Err) const { checkError(std::move(Err)); }
  1130. /// Check E. If it's in a success state then return the contained value. If
  1131. /// it's in a failure state log the error(s) and exit.
  1132. template <typename T> T operator()(Expected<T> &&E) const {
  1133. checkError(E.takeError());
  1134. return std::move(*E);
  1135. }
  1136. /// Check E. If it's in a success state then return the contained reference. If
  1137. /// it's in a failure state log the error(s) and exit.
  1138. template <typename T> T& operator()(Expected<T&> &&E) const {
  1139. checkError(E.takeError());
  1140. return *E;
  1141. }
  1142. private:
  1143. void checkError(Error Err) const {
  1144. if (Err) {
  1145. int ExitCode = GetExitCode(Err);
  1146. logAllUnhandledErrors(std::move(Err), errs(), Banner);
  1147. exit(ExitCode);
  1148. }
  1149. }
  1150. std::string Banner;
  1151. std::function<int(const Error &)> GetExitCode;
  1152. };
  1153. /// Conversion from Error to LLVMErrorRef for C error bindings.
  1154. inline LLVMErrorRef wrap(Error Err) {
  1155. return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
  1156. }
  1157. /// Conversion from LLVMErrorRef to Error for C error bindings.
  1158. inline Error unwrap(LLVMErrorRef ErrRef) {
  1159. return Error(std::unique_ptr<ErrorInfoBase>(
  1160. reinterpret_cast<ErrorInfoBase *>(ErrRef)));
  1161. }
  1162. } // end namespace llvm
  1163. #endif // LLVM_SUPPORT_ERROR_H