Error.h 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  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 <optional>
  38. #include <string>
  39. #include <system_error>
  40. #include <type_traits>
  41. #include <utility>
  42. #include <vector>
  43. namespace llvm {
  44. class ErrorSuccess;
  45. /// Base class for error info classes. Do not extend this directly: Extend
  46. /// the ErrorInfo template subclass instead.
  47. class ErrorInfoBase {
  48. public:
  49. virtual ~ErrorInfoBase() = default;
  50. /// Print an error message to an output stream.
  51. virtual void log(raw_ostream &OS) const = 0;
  52. /// Return the error message as a string.
  53. virtual std::string message() const {
  54. std::string Msg;
  55. raw_string_ostream OS(Msg);
  56. log(OS);
  57. return OS.str();
  58. }
  59. /// Convert this error to a std::error_code.
  60. ///
  61. /// This is a temporary crutch to enable interaction with code still
  62. /// using std::error_code. It will be removed in the future.
  63. virtual std::error_code convertToErrorCode() const = 0;
  64. // Returns the class ID for this type.
  65. static const void *classID() { return &ID; }
  66. // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
  67. virtual const void *dynamicClassID() const = 0;
  68. // Check whether this instance is a subclass of the class identified by
  69. // ClassID.
  70. virtual bool isA(const void *const ClassID) const {
  71. return ClassID == classID();
  72. }
  73. // Check whether this instance is a subclass of ErrorInfoT.
  74. template <typename ErrorInfoT> bool isA() const {
  75. return isA(ErrorInfoT::classID());
  76. }
  77. private:
  78. virtual void anchor();
  79. static char ID;
  80. };
  81. /// Lightweight error class with error context and mandatory checking.
  82. ///
  83. /// Instances of this class wrap a ErrorInfoBase pointer. Failure states
  84. /// are represented by setting the pointer to a ErrorInfoBase subclass
  85. /// instance containing information describing the failure. Success is
  86. /// represented by a null pointer value.
  87. ///
  88. /// Instances of Error also contains a 'Checked' flag, which must be set
  89. /// before the destructor is called, otherwise the destructor will trigger a
  90. /// runtime error. This enforces at runtime the requirement that all Error
  91. /// instances be checked or returned to the caller.
  92. ///
  93. /// There are two ways to set the checked flag, depending on what state the
  94. /// Error instance is in. For Error instances indicating success, it
  95. /// is sufficient to invoke the boolean conversion operator. E.g.:
  96. ///
  97. /// @code{.cpp}
  98. /// Error foo(<...>);
  99. ///
  100. /// if (auto E = foo(<...>))
  101. /// return E; // <- Return E if it is in the error state.
  102. /// // We have verified that E was in the success state. It can now be safely
  103. /// // destroyed.
  104. /// @endcode
  105. ///
  106. /// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
  107. /// without testing the return value will raise a runtime error, even if foo
  108. /// returns success.
  109. ///
  110. /// For Error instances representing failure, you must use either the
  111. /// handleErrors or handleAllErrors function with a typed handler. E.g.:
  112. ///
  113. /// @code{.cpp}
  114. /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
  115. /// // Custom error info.
  116. /// };
  117. ///
  118. /// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
  119. ///
  120. /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
  121. /// auto NewE =
  122. /// handleErrors(E,
  123. /// [](const MyErrorInfo &M) {
  124. /// // Deal with the error.
  125. /// },
  126. /// [](std::unique_ptr<OtherError> M) -> Error {
  127. /// if (canHandle(*M)) {
  128. /// // handle error.
  129. /// return Error::success();
  130. /// }
  131. /// // Couldn't handle this error instance. Pass it up the stack.
  132. /// return Error(std::move(M));
  133. /// );
  134. /// // Note - we must check or return NewE in case any of the handlers
  135. /// // returned a new error.
  136. /// @endcode
  137. ///
  138. /// The handleAllErrors function is identical to handleErrors, except
  139. /// that it has a void return type, and requires all errors to be handled and
  140. /// no new errors be returned. It prevents errors (assuming they can all be
  141. /// handled) from having to be bubbled all the way to the top-level.
  142. ///
  143. /// *All* Error instances must be checked before destruction, even if
  144. /// they're moved-assigned or constructed from Success values that have already
  145. /// been checked. This enforces checking through all levels of the call stack.
  146. class [[nodiscard]] Error {
  147. // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors
  148. // to add to the error list. It can't rely on handleErrors for this, since
  149. // handleErrors does not support ErrorList handlers.
  150. friend class ErrorList;
  151. // handleErrors needs to be able to set the Checked flag.
  152. template <typename... HandlerTs>
  153. friend Error handleErrors(Error E, HandlerTs &&... Handlers);
  154. // Expected<T> needs to be able to steal the payload when constructed from an
  155. // error.
  156. template <typename T> friend class Expected;
  157. // wrap needs to be able to steal the payload.
  158. friend LLVMErrorRef wrap(Error);
  159. protected:
  160. /// Create a success value. Prefer using 'Error::success()' for readability
  161. Error() {
  162. setPtr(nullptr);
  163. setChecked(false);
  164. }
  165. public:
  166. /// Create a success value.
  167. static ErrorSuccess success();
  168. // Errors are not copy-constructable.
  169. Error(const Error &Other) = delete;
  170. /// Move-construct an error value. The newly constructed error is considered
  171. /// unchecked, even if the source error had been checked. The original error
  172. /// becomes a checked Success value, regardless of its original state.
  173. Error(Error &&Other) {
  174. setChecked(true);
  175. *this = std::move(Other);
  176. }
  177. /// Create an error value. Prefer using the 'make_error' function, but
  178. /// this constructor can be useful when "re-throwing" errors from handlers.
  179. Error(std::unique_ptr<ErrorInfoBase> Payload) {
  180. setPtr(Payload.release());
  181. setChecked(false);
  182. }
  183. // Errors are not copy-assignable.
  184. Error &operator=(const Error &Other) = delete;
  185. /// Move-assign an error value. The current error must represent success, you
  186. /// you cannot overwrite an unhandled error. The current error is then
  187. /// considered unchecked. The source error becomes a checked success value,
  188. /// regardless of its original state.
  189. Error &operator=(Error &&Other) {
  190. // Don't allow overwriting of unchecked values.
  191. assertIsChecked();
  192. setPtr(Other.getPtr());
  193. // This Error is unchecked, even if the source error was checked.
  194. setChecked(false);
  195. // Null out Other's payload and set its checked bit.
  196. Other.setPtr(nullptr);
  197. Other.setChecked(true);
  198. return *this;
  199. }
  200. /// Destroy a Error. Fails with a call to abort() if the error is
  201. /// unchecked.
  202. ~Error() {
  203. assertIsChecked();
  204. delete getPtr();
  205. }
  206. /// Bool conversion. Returns true if this Error is in a failure state,
  207. /// and false if it is in an accept state. If the error is in a Success state
  208. /// it will be considered checked.
  209. explicit operator bool() {
  210. setChecked(getPtr() == nullptr);
  211. return getPtr() != nullptr;
  212. }
  213. /// Check whether one error is a subclass of another.
  214. template <typename ErrT> bool isA() const {
  215. return getPtr() && getPtr()->isA(ErrT::classID());
  216. }
  217. /// Returns the dynamic class id of this error, or null if this is a success
  218. /// value.
  219. const void* dynamicClassID() const {
  220. if (!getPtr())
  221. return nullptr;
  222. return getPtr()->dynamicClassID();
  223. }
  224. private:
  225. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  226. // assertIsChecked() happens very frequently, but under normal circumstances
  227. // is supposed to be a no-op. So we want it to be inlined, but having a bunch
  228. // of debug prints can cause the function to be too large for inlining. So
  229. // it's important that we define this function out of line so that it can't be
  230. // inlined.
  231. [[noreturn]] void fatalUncheckedError() const;
  232. #endif
  233. void assertIsChecked() {
  234. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  235. if (LLVM_UNLIKELY(!getChecked() || getPtr()))
  236. fatalUncheckedError();
  237. #endif
  238. }
  239. ErrorInfoBase *getPtr() const {
  240. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  241. return reinterpret_cast<ErrorInfoBase*>(
  242. reinterpret_cast<uintptr_t>(Payload) &
  243. ~static_cast<uintptr_t>(0x1));
  244. #else
  245. return Payload;
  246. #endif
  247. }
  248. void setPtr(ErrorInfoBase *EI) {
  249. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  250. Payload = reinterpret_cast<ErrorInfoBase*>(
  251. (reinterpret_cast<uintptr_t>(EI) &
  252. ~static_cast<uintptr_t>(0x1)) |
  253. (reinterpret_cast<uintptr_t>(Payload) & 0x1));
  254. #else
  255. Payload = EI;
  256. #endif
  257. }
  258. bool getChecked() const {
  259. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  260. return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
  261. #else
  262. return true;
  263. #endif
  264. }
  265. void setChecked(bool V) {
  266. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  267. Payload = reinterpret_cast<ErrorInfoBase*>(
  268. (reinterpret_cast<uintptr_t>(Payload) &
  269. ~static_cast<uintptr_t>(0x1)) |
  270. (V ? 0 : 1));
  271. #endif
  272. }
  273. std::unique_ptr<ErrorInfoBase> takePayload() {
  274. std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
  275. setPtr(nullptr);
  276. setChecked(true);
  277. return Tmp;
  278. }
  279. friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
  280. if (auto *P = E.getPtr())
  281. P->log(OS);
  282. else
  283. OS << "success";
  284. return OS;
  285. }
  286. ErrorInfoBase *Payload = nullptr;
  287. };
  288. /// Subclass of Error for the sole purpose of identifying the success path in
  289. /// the type system. This allows to catch invalid conversion to Expected<T> at
  290. /// compile time.
  291. class ErrorSuccess final : public Error {};
  292. inline ErrorSuccess Error::success() { return ErrorSuccess(); }
  293. /// Make a Error instance representing failure using the given error info
  294. /// type.
  295. template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
  296. return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
  297. }
  298. /// Base class for user error types. Users should declare their error types
  299. /// like:
  300. ///
  301. /// class MyError : public ErrorInfo<MyError> {
  302. /// ....
  303. /// };
  304. ///
  305. /// This class provides an implementation of the ErrorInfoBase::kind
  306. /// method, which is used by the Error RTTI system.
  307. template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
  308. class ErrorInfo : public ParentErrT {
  309. public:
  310. using ParentErrT::ParentErrT; // inherit constructors
  311. static const void *classID() { return &ThisErrT::ID; }
  312. const void *dynamicClassID() const override { return &ThisErrT::ID; }
  313. bool isA(const void *const ClassID) const override {
  314. return ClassID == classID() || ParentErrT::isA(ClassID);
  315. }
  316. };
  317. /// Special ErrorInfo subclass representing a list of ErrorInfos.
  318. /// Instances of this class are constructed by joinError.
  319. class ErrorList final : public ErrorInfo<ErrorList> {
  320. // handleErrors needs to be able to iterate the payload list of an
  321. // ErrorList.
  322. template <typename... HandlerTs>
  323. friend Error handleErrors(Error E, HandlerTs &&... Handlers);
  324. // joinErrors is implemented in terms of join.
  325. friend Error joinErrors(Error, Error);
  326. public:
  327. void log(raw_ostream &OS) const override {
  328. OS << "Multiple errors:\n";
  329. for (const auto &ErrPayload : Payloads) {
  330. ErrPayload->log(OS);
  331. OS << "\n";
  332. }
  333. }
  334. std::error_code convertToErrorCode() const override;
  335. // Used by ErrorInfo::classID.
  336. static char ID;
  337. private:
  338. ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
  339. std::unique_ptr<ErrorInfoBase> Payload2) {
  340. assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
  341. "ErrorList constructor payloads should be singleton errors");
  342. Payloads.push_back(std::move(Payload1));
  343. Payloads.push_back(std::move(Payload2));
  344. }
  345. static Error join(Error E1, Error E2) {
  346. if (!E1)
  347. return E2;
  348. if (!E2)
  349. return E1;
  350. if (E1.isA<ErrorList>()) {
  351. auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
  352. if (E2.isA<ErrorList>()) {
  353. auto E2Payload = E2.takePayload();
  354. auto &E2List = static_cast<ErrorList &>(*E2Payload);
  355. for (auto &Payload : E2List.Payloads)
  356. E1List.Payloads.push_back(std::move(Payload));
  357. } else
  358. E1List.Payloads.push_back(E2.takePayload());
  359. return E1;
  360. }
  361. if (E2.isA<ErrorList>()) {
  362. auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
  363. E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
  364. return E2;
  365. }
  366. return Error(std::unique_ptr<ErrorList>(
  367. new ErrorList(E1.takePayload(), E2.takePayload())));
  368. }
  369. std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
  370. };
  371. /// Concatenate errors. The resulting Error is unchecked, and contains the
  372. /// ErrorInfo(s), if any, contained in E1, followed by the
  373. /// ErrorInfo(s), if any, contained in E2.
  374. inline Error joinErrors(Error E1, Error E2) {
  375. return ErrorList::join(std::move(E1), std::move(E2));
  376. }
  377. /// Tagged union holding either a T or a Error.
  378. ///
  379. /// This class parallels ErrorOr, but replaces error_code with Error. Since
  380. /// Error cannot be copied, this class replaces getError() with
  381. /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
  382. /// error class type.
  383. ///
  384. /// Example usage of 'Expected<T>' as a function return type:
  385. ///
  386. /// @code{.cpp}
  387. /// Expected<int> myDivide(int A, int B) {
  388. /// if (B == 0) {
  389. /// // return an Error
  390. /// return createStringError(inconvertibleErrorCode(),
  391. /// "B must not be zero!");
  392. /// }
  393. /// // return an integer
  394. /// return A / B;
  395. /// }
  396. /// @endcode
  397. ///
  398. /// Checking the results of to a function returning 'Expected<T>':
  399. /// @code{.cpp}
  400. /// if (auto E = Result.takeError()) {
  401. /// // We must consume the error. Typically one of:
  402. /// // - return the error to our caller
  403. /// // - toString(), when logging
  404. /// // - consumeError(), to silently swallow the error
  405. /// // - handleErrors(), to distinguish error types
  406. /// errs() << "Problem with division " << toString(std::move(E)) << "\n";
  407. /// return;
  408. /// }
  409. /// // use the result
  410. /// outs() << "The answer is " << *Result << "\n";
  411. /// @endcode
  412. ///
  413. /// For unit-testing a function returning an 'Expected<T>', see the
  414. /// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h
  415. template <class T> class [[nodiscard]] Expected {
  416. template <class T1> friend class ExpectedAsOutParameter;
  417. template <class OtherT> friend class Expected;
  418. static constexpr bool isRef = std::is_reference<T>::value;
  419. using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
  420. using error_type = std::unique_ptr<ErrorInfoBase>;
  421. public:
  422. using storage_type = std::conditional_t<isRef, wrap, T>;
  423. using value_type = T;
  424. private:
  425. using reference = std::remove_reference_t<T> &;
  426. using const_reference = const std::remove_reference_t<T> &;
  427. using pointer = std::remove_reference_t<T> *;
  428. using const_pointer = const std::remove_reference_t<T> *;
  429. public:
  430. /// Create an Expected<T> error value from the given Error.
  431. Expected(Error Err)
  432. : HasError(true)
  433. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  434. // Expected is unchecked upon construction in Debug builds.
  435. , Unchecked(true)
  436. #endif
  437. {
  438. assert(Err && "Cannot create Expected<T> from Error success value.");
  439. new (getErrorStorage()) error_type(Err.takePayload());
  440. }
  441. /// Forbid to convert from Error::success() implicitly, this avoids having
  442. /// Expected<T> foo() { return Error::success(); } which compiles otherwise
  443. /// but triggers the assertion above.
  444. Expected(ErrorSuccess) = delete;
  445. /// Create an Expected<T> success value from the given OtherT value, which
  446. /// must be convertible to T.
  447. template <typename OtherT>
  448. Expected(OtherT &&Val,
  449. std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr)
  450. : HasError(false)
  451. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  452. // Expected is unchecked upon construction in Debug builds.
  453. ,
  454. Unchecked(true)
  455. #endif
  456. {
  457. new (getStorage()) storage_type(std::forward<OtherT>(Val));
  458. }
  459. /// Move construct an Expected<T> value.
  460. Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
  461. /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
  462. /// must be convertible to T.
  463. template <class OtherT>
  464. Expected(Expected<OtherT> &&Other,
  465. std::enable_if_t<std::is_convertible_v<OtherT, T>> * = 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_v<OtherT, T>> * = 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<
  724. decltype(&std::remove_reference_t<HandlerT>::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 std::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> std::optional<T> expectedToOptional(Expected<T> &&E) {
  924. if (E)
  925. return std::move(*E);
  926. consumeError(E.takeError());
  927. return std::nullopt;
  928. }
  929. template <typename T> std::optional<T> expectedToStdOptional(Expected<T> &&E) {
  930. if (E)
  931. return std::move(*E);
  932. consumeError(E.takeError());
  933. return std::nullopt;
  934. }
  935. /// Helper for converting an Error to a bool.
  936. ///
  937. /// This method returns true if Err is in an error state, or false if it is
  938. /// in a success state. Puts Err in a checked state in both cases (unlike
  939. /// Error::operator bool(), which only does this for success states).
  940. inline bool errorToBool(Error Err) {
  941. bool IsError = static_cast<bool>(Err);
  942. if (IsError)
  943. consumeError(std::move(Err));
  944. return IsError;
  945. }
  946. /// Helper for Errors used as out-parameters.
  947. ///
  948. /// This helper is for use with the Error-as-out-parameter idiom, where an error
  949. /// is passed to a function or method by reference, rather than being returned.
  950. /// In such cases it is helpful to set the checked bit on entry to the function
  951. /// so that the error can be written to (unchecked Errors abort on assignment)
  952. /// and clear the checked bit on exit so that clients cannot accidentally forget
  953. /// to check the result. This helper performs these actions automatically using
  954. /// RAII:
  955. ///
  956. /// @code{.cpp}
  957. /// Result foo(Error &Err) {
  958. /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
  959. /// // <body of foo>
  960. /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
  961. /// }
  962. /// @endcode
  963. ///
  964. /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
  965. /// used with optional Errors (Error pointers that are allowed to be null). If
  966. /// ErrorAsOutParameter took an Error reference, an instance would have to be
  967. /// created inside every condition that verified that Error was non-null. By
  968. /// taking an Error pointer we can just create one instance at the top of the
  969. /// function.
  970. class ErrorAsOutParameter {
  971. public:
  972. ErrorAsOutParameter(Error *Err) : Err(Err) {
  973. // Raise the checked bit if Err is success.
  974. if (Err)
  975. (void)!!*Err;
  976. }
  977. ~ErrorAsOutParameter() {
  978. // Clear the checked bit.
  979. if (Err && !*Err)
  980. *Err = Error::success();
  981. }
  982. private:
  983. Error *Err;
  984. };
  985. /// Helper for Expected<T>s used as out-parameters.
  986. ///
  987. /// See ErrorAsOutParameter.
  988. template <typename T>
  989. class ExpectedAsOutParameter {
  990. public:
  991. ExpectedAsOutParameter(Expected<T> *ValOrErr)
  992. : ValOrErr(ValOrErr) {
  993. if (ValOrErr)
  994. (void)!!*ValOrErr;
  995. }
  996. ~ExpectedAsOutParameter() {
  997. if (ValOrErr)
  998. ValOrErr->setUnchecked();
  999. }
  1000. private:
  1001. Expected<T> *ValOrErr;
  1002. };
  1003. /// This class wraps a std::error_code in a Error.
  1004. ///
  1005. /// This is useful if you're writing an interface that returns a Error
  1006. /// (or Expected) and you want to call code that still returns
  1007. /// std::error_codes.
  1008. class ECError : public ErrorInfo<ECError> {
  1009. friend Error errorCodeToError(std::error_code);
  1010. void anchor() override;
  1011. public:
  1012. void setErrorCode(std::error_code EC) { this->EC = EC; }
  1013. std::error_code convertToErrorCode() const override { return EC; }
  1014. void log(raw_ostream &OS) const override { OS << EC.message(); }
  1015. // Used by ErrorInfo::classID.
  1016. static char ID;
  1017. protected:
  1018. ECError() = default;
  1019. ECError(std::error_code EC) : EC(EC) {}
  1020. std::error_code EC;
  1021. };
  1022. /// The value returned by this function can be returned from convertToErrorCode
  1023. /// for Error values where no sensible translation to std::error_code exists.
  1024. /// It should only be used in this situation, and should never be used where a
  1025. /// sensible conversion to std::error_code is available, as attempts to convert
  1026. /// to/from this error will result in a fatal error. (i.e. it is a programmatic
  1027. /// error to try to convert such a value).
  1028. std::error_code inconvertibleErrorCode();
  1029. /// Helper for converting an std::error_code to a Error.
  1030. Error errorCodeToError(std::error_code EC);
  1031. /// Helper for converting an ECError to a std::error_code.
  1032. ///
  1033. /// This method requires that Err be Error() or an ECError, otherwise it
  1034. /// will trigger a call to abort().
  1035. std::error_code errorToErrorCode(Error Err);
  1036. /// Convert an ErrorOr<T> to an Expected<T>.
  1037. template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
  1038. if (auto EC = EO.getError())
  1039. return errorCodeToError(EC);
  1040. return std::move(*EO);
  1041. }
  1042. /// Convert an Expected<T> to an ErrorOr<T>.
  1043. template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
  1044. if (auto Err = E.takeError())
  1045. return errorToErrorCode(std::move(Err));
  1046. return std::move(*E);
  1047. }
  1048. /// This class wraps a string in an Error.
  1049. ///
  1050. /// StringError is useful in cases where the client is not expected to be able
  1051. /// to consume the specific error message programmatically (for example, if the
  1052. /// error message is to be presented to the user).
  1053. ///
  1054. /// StringError can also be used when additional information is to be printed
  1055. /// along with a error_code message. Depending on the constructor called, this
  1056. /// class can either display:
  1057. /// 1. the error_code message (ECError behavior)
  1058. /// 2. a string
  1059. /// 3. the error_code message and a string
  1060. ///
  1061. /// These behaviors are useful when subtyping is required; for example, when a
  1062. /// specific library needs an explicit error type. In the example below,
  1063. /// PDBError is derived from StringError:
  1064. ///
  1065. /// @code{.cpp}
  1066. /// Expected<int> foo() {
  1067. /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
  1068. /// "Additional information");
  1069. /// }
  1070. /// @endcode
  1071. ///
  1072. class StringError : public ErrorInfo<StringError> {
  1073. public:
  1074. static char ID;
  1075. // Prints EC + S and converts to EC
  1076. StringError(std::error_code EC, const Twine &S = Twine());
  1077. // Prints S and converts to EC
  1078. StringError(const Twine &S, std::error_code EC);
  1079. void log(raw_ostream &OS) const override;
  1080. std::error_code convertToErrorCode() const override;
  1081. const std::string &getMessage() const { return Msg; }
  1082. private:
  1083. std::string Msg;
  1084. std::error_code EC;
  1085. const bool PrintMsgOnly = false;
  1086. };
  1087. /// Create formatted StringError object.
  1088. template <typename... Ts>
  1089. inline Error createStringError(std::error_code EC, char const *Fmt,
  1090. const Ts &... Vals) {
  1091. std::string Buffer;
  1092. raw_string_ostream Stream(Buffer);
  1093. Stream << format(Fmt, Vals...);
  1094. return make_error<StringError>(Stream.str(), EC);
  1095. }
  1096. Error createStringError(std::error_code EC, char const *Msg);
  1097. inline Error createStringError(std::error_code EC, const Twine &S) {
  1098. return createStringError(EC, S.str().c_str());
  1099. }
  1100. template <typename... Ts>
  1101. inline Error createStringError(std::errc EC, char const *Fmt,
  1102. const Ts &... Vals) {
  1103. return createStringError(std::make_error_code(EC), Fmt, Vals...);
  1104. }
  1105. /// This class wraps a filename and another Error.
  1106. ///
  1107. /// In some cases, an error needs to live along a 'source' name, in order to
  1108. /// show more detailed information to the user.
  1109. class FileError final : public ErrorInfo<FileError> {
  1110. friend Error createFileError(const Twine &, Error);
  1111. friend Error createFileError(const Twine &, size_t, Error);
  1112. public:
  1113. void log(raw_ostream &OS) const override {
  1114. assert(Err && "Trying to log after takeError().");
  1115. OS << "'" << FileName << "': ";
  1116. if (Line)
  1117. OS << "line " << *Line << ": ";
  1118. Err->log(OS);
  1119. }
  1120. std::string messageWithoutFileInfo() const {
  1121. std::string Msg;
  1122. raw_string_ostream OS(Msg);
  1123. Err->log(OS);
  1124. return OS.str();
  1125. }
  1126. StringRef getFileName() const { return FileName; }
  1127. Error takeError() { return Error(std::move(Err)); }
  1128. std::error_code convertToErrorCode() const override;
  1129. // Used by ErrorInfo::classID.
  1130. static char ID;
  1131. private:
  1132. FileError(const Twine &F, std::optional<size_t> LineNum,
  1133. std::unique_ptr<ErrorInfoBase> E) {
  1134. assert(E && "Cannot create FileError from Error success value.");
  1135. FileName = F.str();
  1136. Err = std::move(E);
  1137. Line = std::move(LineNum);
  1138. }
  1139. static Error build(const Twine &F, std::optional<size_t> Line, Error E) {
  1140. std::unique_ptr<ErrorInfoBase> Payload;
  1141. handleAllErrors(std::move(E),
  1142. [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error {
  1143. Payload = std::move(EIB);
  1144. return Error::success();
  1145. });
  1146. return Error(
  1147. std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload))));
  1148. }
  1149. std::string FileName;
  1150. std::optional<size_t> Line;
  1151. std::unique_ptr<ErrorInfoBase> Err;
  1152. };
  1153. /// Concatenate a source file path and/or name with an Error. The resulting
  1154. /// Error is unchecked.
  1155. inline Error createFileError(const Twine &F, Error E) {
  1156. return FileError::build(F, std::optional<size_t>(), std::move(E));
  1157. }
  1158. /// Concatenate a source file path and/or name with line number and an Error.
  1159. /// The resulting Error is unchecked.
  1160. inline Error createFileError(const Twine &F, size_t Line, Error E) {
  1161. return FileError::build(F, std::optional<size_t>(Line), std::move(E));
  1162. }
  1163. /// Concatenate a source file path and/or name with a std::error_code
  1164. /// to form an Error object.
  1165. inline Error createFileError(const Twine &F, std::error_code EC) {
  1166. return createFileError(F, errorCodeToError(EC));
  1167. }
  1168. /// Concatenate a source file path and/or name with line number and
  1169. /// std::error_code to form an Error object.
  1170. inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
  1171. return createFileError(F, Line, errorCodeToError(EC));
  1172. }
  1173. Error createFileError(const Twine &F, ErrorSuccess) = delete;
  1174. /// Helper for check-and-exit error handling.
  1175. ///
  1176. /// For tool use only. NOT FOR USE IN LIBRARY CODE.
  1177. ///
  1178. class ExitOnError {
  1179. public:
  1180. /// Create an error on exit helper.
  1181. ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
  1182. : Banner(std::move(Banner)),
  1183. GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
  1184. /// Set the banner string for any errors caught by operator().
  1185. void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
  1186. /// Set the exit-code mapper function.
  1187. void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
  1188. this->GetExitCode = std::move(GetExitCode);
  1189. }
  1190. /// Check Err. If it's in a failure state log the error(s) and exit.
  1191. void operator()(Error Err) const { checkError(std::move(Err)); }
  1192. /// Check E. If it's in a success state then return the contained value. 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 std::move(*E);
  1197. }
  1198. /// Check E. If it's in a success state then return the contained reference. If
  1199. /// it's in a failure state log the error(s) and exit.
  1200. template <typename T> T& operator()(Expected<T&> &&E) const {
  1201. checkError(E.takeError());
  1202. return *E;
  1203. }
  1204. private:
  1205. void checkError(Error Err) const {
  1206. if (Err) {
  1207. int ExitCode = GetExitCode(Err);
  1208. logAllUnhandledErrors(std::move(Err), errs(), Banner);
  1209. exit(ExitCode);
  1210. }
  1211. }
  1212. std::string Banner;
  1213. std::function<int(const Error &)> GetExitCode;
  1214. };
  1215. /// Conversion from Error to LLVMErrorRef for C error bindings.
  1216. inline LLVMErrorRef wrap(Error Err) {
  1217. return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
  1218. }
  1219. /// Conversion from LLVMErrorRef to Error for C error bindings.
  1220. inline Error unwrap(LLVMErrorRef ErrRef) {
  1221. return Error(std::unique_ptr<ErrorInfoBase>(
  1222. reinterpret_cast<ErrorInfoBase *>(ErrRef)));
  1223. }
  1224. } // end namespace llvm
  1225. #endif // LLVM_SUPPORT_ERROR_H
  1226. #ifdef __GNUC__
  1227. #pragma GCC diagnostic pop
  1228. #endif