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