Error.h 45 KB

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