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