Error.h 44 KB

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