1//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// 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 7//===----------------------------------------------------------------------===// 9// This file defines an API used to report recoverable errors. 11//===----------------------------------------------------------------------===// 13#ifndef LLVM_SUPPORT_ERROR_H 14#define LLVM_SUPPORT_ERROR_H 18#include "llvm/Config/abi-breaking.h" 34#include <system_error> 43/// Base class for error info classes. Do not extend this directly: Extend 44/// the ErrorInfo template subclass instead. 49 /// Print an error message to an output stream. 52 /// Return the error message as a string. 60 /// Convert this error to a std::error_code. 62 /// This is a temporary crutch to enable interaction with code still 63 /// using std::error_code. It will be removed in the future. 66// Returns the class ID for this type. 69// Returns the class ID for the dynamic type of this ErrorInfoBase instance. 72// Check whether this instance is a subclass of the class identified by 74virtualboolisA(
constvoid *
const ClassID)
const{
78// Check whether this instance is a subclass of ErrorInfoT. 79template <
typename ErrorInfoT>
boolisA()
const{
80returnisA(ErrorInfoT::classID());
89/// Lightweight error class with error context and mandatory checking. 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. 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. 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.: 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 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 118/// For Error instances representing failure, you must use either the 119/// handleErrors or handleAllErrors function with a typed handler. E.g.: 122/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { 123/// // Custom error info. 126/// Error foo(<...>) { return make_error<MyErrorInfo>(...); } 128/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. 130/// handleErrors(std::move(E), 131/// [](const MyErrorInfo &M) { 132/// // Deal with the error. 134/// [](std::unique_ptr<OtherError> M) -> Error { 135/// if (canHandle(*M)) { 137/// return Error::success(); 139/// // Couldn't handle this error instance. Pass it up the stack. 140/// return Error(std::move(M)); 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. 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. 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. 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. 166// handleErrors needs to be able to set the Checked flag. 167template <
typename... HandlerTs>
169// visitErrors needs direct access to the payload. 170template <
typename HandlerT>
173// Expected<T> needs to be able to steal the payload when constructed from an 177// wrap needs to be able to steal the payload. 181 /// Create a success value. Prefer using 'Error::success()' for readability 188 /// Create a success value. 191// Errors are not copy-constructable. 194 /// Move-construct an error value. The newly constructed error is considered 195 /// unchecked, even if the source error had been checked. The original error 196 /// becomes a checked Success value, regardless of its original state. 199 *
this = std::move(
Other);
202 /// Create an error value. Prefer using the 'make_error' function, but 203 /// this constructor can be useful when "re-throwing" errors from handlers. 204Error(std::unique_ptr<ErrorInfoBase> Payload) {
205 setPtr(Payload.release());
209// Errors are not copy-assignable. 212 /// Move-assign an error value. The current error must represent success, you 213 /// you cannot overwrite an unhandled error. The current error is then 214 /// considered unchecked. The source error becomes a checked success value, 215 /// regardless of its original state. 217// Don't allow overwriting of unchecked values. 219 setPtr(
Other.getPtr());
221// This Error is unchecked, even if the source error was checked. 224// Null out Other's payload and set its checked bit. 225Other.setPtr(
nullptr);
226Other.setChecked(
true);
231 /// Destroy a Error. Fails with a call to abort() if the error is 238 /// Bool conversion. Returns true if this Error is in a failure state, 239 /// and false if it is in an accept state. If the error is in a Success state 240 /// it will be considered checked. 242 setChecked(
getPtr() ==
nullptr);
246 /// Check whether one error is a subclass of another. 247template <
typename ErrT>
boolisA()
const{
251 /// Returns the dynamic class id of this error, or null if this is a success 256returngetPtr()->dynamicClassID();
260#if LLVM_ENABLE_ABI_BREAKING_CHECKS 261// assertIsChecked() happens very frequently, but under normal circumstances 262// is supposed to be a no-op. So we want it to be inlined, but having a bunch 263// of debug prints can cause the function to be too large for inlining. So 264// it's important that we define this function out of line so that it can't be 266 [[noreturn]]
void fatalUncheckedError()
const;
269void assertIsChecked() {
270#if LLVM_ENABLE_ABI_BREAKING_CHECKS 272 fatalUncheckedError();
276 ErrorInfoBase *
getPtr()
const{
277#if LLVM_ENABLE_ABI_BREAKING_CHECKS 278returnreinterpret_cast<ErrorInfoBase*
>(
279reinterpret_cast<uintptr_t
>(Payload) &
280 ~
static_cast<uintptr_t
>(0x1));
286void setPtr(ErrorInfoBase *EI) {
287#if LLVM_ENABLE_ABI_BREAKING_CHECKS 288 Payload =
reinterpret_cast<ErrorInfoBase*
>(
289 (
reinterpret_cast<uintptr_t
>(EI) &
290 ~
static_cast<uintptr_t
>(0x1)) |
291 (
reinterpret_cast<uintptr_t
>(Payload) & 0x1));
297bool getChecked()
const{
298#if LLVM_ENABLE_ABI_BREAKING_CHECKS 299return (
reinterpret_cast<uintptr_t
>(Payload) & 0x1) == 0;
305void setChecked(
bool V) {
306#if LLVM_ENABLE_ABI_BREAKING_CHECKS 307 Payload =
reinterpret_cast<ErrorInfoBase*
>(
308 (
reinterpret_cast<uintptr_t
>(Payload) &
309 ~
static_cast<uintptr_t
>(0x1)) |
314 std::unique_ptr<ErrorInfoBase> takePayload() {
315 std::unique_ptr<ErrorInfoBase> Tmp(
getPtr());
322if (
auto *
P =
E.getPtr())
332/// Subclass of Error for the sole purpose of identifying the success path in 333/// the type system. This allows to catch invalid conversion to Expected<T> at 339/// Make a Error instance representing failure using the given error info 342returnError(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
345/// Base class for user error types. Users should declare their error types 348/// class MyError : public ErrorInfo<MyError> { 352/// This class provides an implementation of the ErrorInfoBase::kind 353/// method, which is used by the Error RTTI system. 354template <
typename ThisErrT,
typename ParentErrT = ErrorInfoBase>
357usingParentErrT::ParentErrT;
// inherit constructors 359staticconstvoid *
classID() {
return &ThisErrT::ID; }
363boolisA(
constvoid *
const ClassID)
const override{
364return ClassID ==
classID() || ParentErrT::isA(ClassID);
368/// Special ErrorInfo subclass representing a list of ErrorInfos. 369/// Instances of this class are constructed by joinError. 371// handleErrors needs to be able to iterate the payload list of an 373template <
typename... HandlerTs>
375// visitErrors needs to be able to iterate the payload list of an 377template <
typename HandlerT>
380// joinErrors is implemented in terms of join. 385OS <<
"Multiple errors:\n";
386for (
constauto &ErrPayload : Payloads) {
394// Used by ErrorInfo::classID. 398ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
399 std::unique_ptr<ErrorInfoBase> Payload2) {
401"ErrorList constructor payloads should be singleton errors");
402 Payloads.push_back(std::move(Payload1));
403 Payloads.push_back(std::move(Payload2));
412auto &E1List =
static_cast<ErrorList &
>(*E1.getPtr());
414auto E2Payload = E2.takePayload();
415auto &E2List =
static_cast<ErrorList &
>(*E2Payload);
416for (
auto &Payload : E2List.Payloads)
417 E1List.Payloads.push_back(std::move(Payload));
419 E1List.Payloads.push_back(E2.takePayload());
423if (E2.
isA<ErrorList>()) {
424auto &E2List =
static_cast<ErrorList &
>(*E2.getPtr());
425 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
428returnError(std::unique_ptr<ErrorList>(
429new ErrorList(E1.takePayload(), E2.takePayload())));
432 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
435/// Concatenate errors. The resulting Error is unchecked, and contains the 436/// ErrorInfo(s), if any, contained in E1, followed by the 437/// ErrorInfo(s), if any, contained in E2. 439return ErrorList::join(std::move(E1), std::move(E2));
442/// Tagged union holding either a T or a Error. 444/// This class parallels ErrorOr, but replaces error_code with Error. Since 445/// Error cannot be copied, this class replaces getError() with 446/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the 449/// Example usage of 'Expected<T>' as a function return type: 452/// Expected<int> myDivide(int A, int B) { 454/// // return an Error 455/// return createStringError(inconvertibleErrorCode(), 456/// "B must not be zero!"); 458/// // return an integer 463/// Checking the results of to a function returning 'Expected<T>': 465/// if (auto E = Result.takeError()) { 466/// // We must consume the error. Typically one of: 467/// // - return the error to our caller 468/// // - toString(), when logging 469/// // - consumeError(), to silently swallow the error 470/// // - handleErrors(), to distinguish error types 471/// errs() << "Problem with division " << toString(std::move(E)) << "\n"; 475/// outs() << "The answer is " << *Result << "\n"; 478/// For unit-testing a function returning an 'Expected<T>', see the 479/// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h 485staticconstexprbool isRef = std::is_reference_v<T>;
487usingwrap = std::reference_wrapper<std::remove_reference_t<T>>;
489usingerror_type = std::unique_ptr<ErrorInfoBase>;
496usingreference = std::remove_reference_t<T> &;
497usingconst_reference =
const std::remove_reference_t<T> &;
498usingpointer = std::remove_reference_t<T> *;
499usingconst_pointer =
const std::remove_reference_t<T> *;
502 /// Create an Expected<T> error value from the given Error. 505#
if LLVM_ENABLE_ABI_BREAKING_CHECKS
506// Expected is unchecked upon construction in Debug builds. 510assert(Err &&
"Cannot create Expected<T> from Error success value.");
511new (getErrorStorage()) error_type(Err.takePayload());
514 /// Forbid to convert from Error::success() implicitly, this avoids having 515 /// Expected<T> foo() { return Error::success(); } which compiles otherwise 516 /// but triggers the assertion above. 519 /// Create an Expected<T> success value from the given OtherT value, which 520 /// must be convertible to T. 521template <
typename OtherT>
523 std::enable_if_t<std::is_convertible_v<OtherT, T>> * =
nullptr)
525#
if LLVM_ENABLE_ABI_BREAKING_CHECKS
526// Expected is unchecked upon construction in Debug builds. 531new (getStorage())
storage_type(std::forward<OtherT>(Val));
534 /// Move construct an Expected<T> value. 537 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT 538 /// must be convertible to T. 539template <
class OtherT>
541 std::enable_if_t<std::is_convertible_v<OtherT, T>> * =
nullptr) {
542 moveConstruct(std::move(
Other));
545 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT 546 /// isn't convertible to T. 547template <
class OtherT>
550 std::enable_if_t<!std::is_convertible_v<OtherT, T>> * =
nullptr) {
551 moveConstruct(std::move(
Other));
554 /// Move-assign from another Expected<T>. 556 moveAssign(std::move(
Other));
560 /// Destroy an Expected<T>. 564 getStorage()->~storage_type();
566 getErrorStorage()->~error_type();
569 /// Return false if there is an error. 571#if LLVM_ENABLE_ABI_BREAKING_CHECKS 577 /// Returns a reference to the stored T value. 583 /// Returns a const reference to the stored T value. 584 const_reference
get()
const{
589 /// Returns \a takeError() after moving the held T (if any) into \p V. 590template <
class OtherT>
593 std::enable_if_t<std::is_assignable_v<OtherT &, T &&>> * =
nullptr) && {
599 /// Check that this Expected<T> is an error of type ErrT. 601return HasError && (*getErrorStorage())->
template isA<ErrT>();
604 /// Take ownership of the stored error. 605 /// After calling this the Expected<T> is in an indeterminate state that can 606 /// only be safely destructed. No further calls (beside the destructor) should 607 /// be made on the Expected<T> value. 609#if LLVM_ENABLE_ABI_BREAKING_CHECKS 612return HasError ?
Error(std::move(*getErrorStorage())) : Error::success();
615 /// Returns a pointer to the stored T value. 618return toPointer(getStorage());
621 /// Returns a const pointer to the stored T value. 624return toPointer(getStorage());
627 /// Returns a reference to the stored T value. 633 /// Returns a const reference to the stored T value. 641staticbool compareThisIfSameType(
constT1 &a,
constT1 &b) {
645template <
class T1,
class T2>
646staticbool compareThisIfSameType(
constT1 &,
const T2 &) {
650template <
class OtherT>
void moveConstruct(Expected<OtherT> &&
Other) {
651 HasError =
Other.HasError;
652#if LLVM_ENABLE_ABI_BREAKING_CHECKS 654Other.Unchecked =
false;
658new (getStorage()) storage_type(std::move(*
Other.getStorage()));
660new (getErrorStorage()) error_type(std::move(*
Other.getErrorStorage()));
663template <
class OtherT>
void moveAssign(Expected<OtherT> &&
Other) {
666if (compareThisIfSameType(*
this,
Other))
670new (
this) Expected(std::move(
Other));
673 pointer toPointer(pointer Val) {
return Val; }
675 const_pointer toPointer(const_pointer Val)
const{
return Val; }
677 pointer toPointer(
wrap *Val) {
return &Val->get(); }
679 const_pointer toPointer(
constwrap *Val)
const{
return &Val->get(); }
681 storage_type *getStorage() {
682assert(!HasError &&
"Cannot get value when an error exists!");
683returnreinterpret_cast<storage_type *
>(&TStorage);
686const storage_type *getStorage()
const{
687assert(!HasError &&
"Cannot get value when an error exists!");
688returnreinterpret_cast<conststorage_type *
>(&TStorage);
691 error_type *getErrorStorage() {
692assert(HasError &&
"Cannot get error when a value exists!");
693returnreinterpret_cast<error_type *
>(&ErrorStorage);
696const error_type *getErrorStorage()
const{
697assert(HasError &&
"Cannot get error when a value exists!");
698returnreinterpret_cast<consterror_type *
>(&ErrorStorage);
701// Used by ExpectedAsOutParameter to reset the checked flag. 703#if LLVM_ENABLE_ABI_BREAKING_CHECKS 708#if LLVM_ENABLE_ABI_BREAKING_CHECKS 710dbgs() <<
"Expected<T> must be checked before access or destruction.\n";
712dbgs() <<
"Unchecked Expected<T> contained error:\n";
713 (*getErrorStorage())->log(
dbgs());
715dbgs() <<
"Expected<T> value was in success state. (Note: Expected<T> " 716"values in success mode must still be checked prior to being " 722void assertIsChecked()
const{
723#if LLVM_ENABLE_ABI_BREAKING_CHECKS 725 fatalUncheckedExpected();
734#if LLVM_ENABLE_ABI_BREAKING_CHECKS 739/// Report a serious error, calling any installed error handler. See 743/// Report a fatal error if Err is a failure value. 745/// This function can be used to wrap calls to fallible functions ONLY when it 746/// is known that the Error will always be a success value. E.g. 749/// // foo only attempts the fallible operation if DoFallibleOperation is 750/// // true. If DoFallibleOperation is false then foo always returns 751/// // Error::success(). 752/// Error foo(bool DoFallibleOperation); 754/// cantFail(foo(false)); 759 Msg =
"Failure value returned from cantFail wrapped call";
763OS << Msg <<
"\n" << Err;
770/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and 771/// returns the contained value. 773/// This function can be used to wrap calls to fallible functions ONLY when it 774/// is known that the Error will always be a success value. E.g. 777/// // foo only attempts the fallible operation if DoFallibleOperation is 778/// // true. If DoFallibleOperation is false then foo always returns an int. 779/// Expected<int> foo(bool DoFallibleOperation); 781/// int X = cantFail(foo(false)); 786return std::move(*ValOrErr);
789 Msg =
"Failure value returned from cantFail wrapped call";
793autoE = ValOrErr.takeError();
801/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and 802/// returns the contained reference. 804/// This function can be used to wrap calls to fallible functions ONLY when it 805/// is known that the Error will always be a success value. E.g. 808/// // foo only attempts the fallible operation if DoFallibleOperation is 809/// // true. If DoFallibleOperation is false then foo always returns a Bar&. 810/// Expected<Bar&> foo(bool DoFallibleOperation); 812/// Bar &X = cantFail(foo(false)); 820 Msg =
"Failure value returned from cantFail wrapped call";
824autoE = ValOrErr.takeError();
832/// Helper for testing applicability of, and applying, handlers for 834template <
typename HandlerT>
837 decltype(&std::remove_reference_t<HandlerT>::operator())> {};
839// Specialization functions of the form 'Error (const ErrT&)'. 843returnE.template isA<ErrT>();
846template <
typename HandlerT>
848assert(appliesTo(*
E) &&
"Applying incorrect handler");
849returnH(
static_cast<ErrT &
>(*
E));
853// Specialization functions of the form 'void (const ErrT&)'. 857returnE.template isA<ErrT>();
860template <
typename HandlerT>
862assert(appliesTo(*
E) &&
"Applying incorrect handler");
863H(
static_cast<ErrT &
>(*
E));
868/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. 869template <
typename ErrT>
873returnE.template isA<ErrT>();
876template <
typename HandlerT>
878assert(appliesTo(*
E) &&
"Applying incorrect handler");
879 std::unique_ptr<ErrT> SubE(
static_cast<ErrT *
>(
E.release()));
880returnH(std::move(SubE));
884/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. 885template <
typename ErrT>
889returnE.template isA<ErrT>();
892template <
typename HandlerT>
894assert(appliesTo(*
E) &&
"Applying incorrect handler");
895 std::unique_ptr<ErrT> SubE(
static_cast<ErrT *
>(
E.release()));
901// Specialization for member functions of the form 'RetT (const ErrT&)'. 902template <
typename C,
typename RetT,
typename ErrT>
906// Specialization for member functions of the form 'RetT (const ErrT&) const'. 907template <
typename C,
typename RetT,
typename ErrT>
911// Specialization for member functions of the form 'RetT (const ErrT&)'. 912template <
typename C,
typename RetT,
typename ErrT>
916// Specialization for member functions of the form 'RetT (const ErrT&) const'. 917template <
typename C,
typename RetT,
typename ErrT>
921/// Specialization for member functions of the form 922/// 'RetT (std::unique_ptr<ErrT>)'. 923template <
typename C,
typename RetT,
typename ErrT>
927/// Specialization for member functions of the form 928/// 'RetT (std::unique_ptr<ErrT>) const'. 929template <
typename C,
typename RetT,
typename ErrT>
934returnError(std::move(Payload));
937template <
typename HandlerT,
typename... HandlerTs>
939 HandlerT &&Handler, HandlerTs &&... Handlers) {
944 std::forward<HandlerTs>(Handlers)...);
947/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any 948/// unhandled errors (or Errors returned by handlers) are re-concatenated and 950/// Because this function returns an error, its result must also be checked 951/// or returned. If you intend to handle all errors use handleAllErrors 952/// (which returns void, and will abort() on unhandled errors) instead. 953template <
typename... HandlerTs>
958 std::unique_ptr<ErrorInfoBase> Payload =
E.takePayload();
963for (
auto &
P :
List.Payloads)
970returnhandleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
973/// Behaves the same as handleErrors, except that by contract all errors 974/// *must* be handled by the given handlers (i.e. there must be no remaining 975/// errors after running the handlers, or llvm_unreachable is called). 976template <
typename... HandlerTs>
981/// Check that E is a non-error, then drop it. 982/// If E is an error, llvm_unreachable will be called. 987/// Visit all the ErrorInfo(s) contained in E by passing them to the respective 988/// handler, without consuming the error. 996for (
constauto &
P :
List.Payloads)
1004/// Handle any errors (if present) in an Expected<T>, then try a recovery path. 1006/// If the incoming value is a success value it is returned unmodified. If it 1007/// is a failure value then it the contained error is passed to handleErrors. 1008/// If handleErrors is able to handle the error then the RecoveryPath functor 1009/// is called to supply the final result. If handleErrors is not able to 1010/// handle all errors then the unhandled errors are returned. 1012/// This utility enables the follow pattern: 1015/// enum FooStrategy { Aggressive, Conservative }; 1016/// Expected<Foo> foo(FooStrategy S); 1018/// auto ResultOrErr = 1021/// []() { return foo(Conservative); }, 1022/// [](AggressiveStrategyError&) { 1023/// // Implicitly conusme this - we'll recover by using a conservative 1028template <
typenameT,
typename RecoveryFtor,
typename... HandlerTs>
1030 HandlerTs &&... Handlers) {
1035 std::forward<HandlerTs>(Handlers)...))
1036return std::move(Err);
1038return RecoveryPath();
1041/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner 1042/// will be printed before the first one is logged. A newline will be printed 1043/// after each error. 1045/// This function is compatible with the helpers from Support/WithColor.h. You 1046/// can pass any of them as the OS. Please consider using them instead of 1047/// including 'error: ' in the ErrorBanner. 1049/// This is useful in the base level of your program to allow clean termination 1050/// (allowing clean deallocation of resources, etc.), while reporting error 1051/// information to the user. 1054/// Write all error messages (if any) in E to a string. The newline character 1055/// is used to separate error messages. 1058/// Like toString(), but does not consume the error. This can be used to print 1059/// a warning while retaining the original error object. 1062/// Consume a Error without doing anything. This method should be used 1063/// only where an error can be considered a reasonable and expected return 1066/// Uses of this method are potentially indicative of design problems: If it's 1067/// legitimate to do nothing while processing an "error", the error-producer 1068/// might be more clearly refactored to return an std::optional<T>. 1073/// Convert an Expected to an Optional without doing anything. This method 1074/// should be used only where an error can be considered a reasonable and 1075/// expected return value. 1077/// Uses of this method are potentially indicative of problems: perhaps the 1078/// error should be propagated further, or the error-producer should just 1079/// return an Optional in the first place. 1082return std::move(*
E);
1089return std::move(*
E);
1094/// Helper for converting an Error to a bool. 1096/// This method returns true if Err is in an error state, or false if it is 1097/// in a success state. Puts Err in a checked state in both cases (unlike 1098/// Error::operator bool(), which only does this for success states). 1100bool IsError =
static_cast<bool>(Err);
1106/// Helper for Errors used as out-parameters. 1108/// This helper is for use with the Error-as-out-parameter idiom, where an error 1109/// is passed to a function or method by reference, rather than being returned. 1110/// In such cases it is helpful to set the checked bit on entry to the function 1111/// so that the error can be written to (unchecked Errors abort on assignment) 1112/// and clear the checked bit on exit so that clients cannot accidentally forget 1113/// to check the result. This helper performs these actions automatically using 1117/// Result foo(Error &Err) { 1118/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set 1120/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. 1124/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be 1125/// used with optional Errors (Error pointers that are allowed to be null). If 1126/// ErrorAsOutParameter took an Error reference, an instance would have to be 1127/// created inside every condition that verified that Error was non-null. By 1128/// taking an Error pointer we can just create one instance at the top of the 1134// Raise the checked bit if Err is success. 1144// Clear the checked bit. 1153/// Helper for Expected<T>s used as out-parameters. 1155/// See ErrorAsOutParameter. 1156template <
typename T>
1160 : ValOrErr(ValOrErr) {
1167 ValOrErr->setUnchecked();
1174/// This class wraps a std::error_code in a Error. 1176/// This is useful if you're writing an interface that returns a Error 1177/// (or Expected) and you want to call code that still returns 1178/// std::error_codes. 1182void anchor()
override;
1189// Used by ErrorInfo::classID. 1199/// The value returned by this function can be returned from convertToErrorCode 1200/// for Error values where no sensible translation to std::error_code exists. 1201/// It should only be used in this situation, and should never be used where a 1202/// sensible conversion to std::error_code is available, as attempts to convert 1203/// to/from this error will result in a fatal error. (i.e. it is a programmatic 1204/// error to try to convert such a value). 1207/// Helper for converting an std::error_code to a Error. 1210/// Helper for converting an ECError to a std::error_code. 1212/// This method requires that Err be Error() or an ECError, otherwise it 1213/// will trigger a call to abort(). 1216/// Helper to get errno as an std::error_code. 1218/// errno should always be represented using the generic category as that's what 1219/// both libc++ and libstdc++ do. On POSIX systems you can also represent them 1220/// using the system category, however this makes them compare differently for 1221/// values outside of those used by `std::errc` if one is generic and the other 1224/// See the libc++ and libstdc++ implementations of `default_error_condition` on 1225/// the system category for more details on what the difference is. 1227return std::error_code(errno, std::generic_category());
1230/// Convert an ErrorOr<T> to an Expected<T>. 1232if (
auto EC = EO.getError())
1234return std::move(*EO);
1237/// Convert an Expected<T> to an ErrorOr<T>. 1239if (
auto Err =
E.takeError())
1241return std::move(*
E);
1244/// This class wraps a string in an Error. 1246/// StringError is useful in cases where the client is not expected to be able 1247/// to consume the specific error message programmatically (for example, if the 1248/// error message is to be presented to the user). 1250/// StringError can also be used when additional information is to be printed 1251/// along with a error_code message. Depending on the constructor called, this 1252/// class can either display: 1253/// 1. the error_code message (ECError behavior) 1255/// 3. the error_code message and a string 1257/// These behaviors are useful when subtyping is required; for example, when a 1258/// specific library needs an explicit error type. In the example below, 1259/// PDBError is derived from StringError: 1262/// Expected<int> foo() { 1263/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, 1264/// "Additional information"); 1272StringError(std::string &&S, std::error_code EC,
bool PrintMsgOnly);
1273 /// Prints EC + S and converts to EC. 1275 /// Prints S and converts to EC. 1286constbool PrintMsgOnly =
false;
1289/// Create formatted StringError object. 1290template <
typename... Ts>
1292const Ts &... Vals) {
1295return make_error<StringError>(Buffer, EC);
1308/// Create a StringError with an inconvertible error code. 1313template <
typename... Ts>
1318template <
typename... Ts>
1320const Ts &... Vals) {
1324/// This class wraps a filename and another Error. 1326/// In some cases, an error needs to live along a 'source' name, in order to 1327/// show more detailed information to the user. 1335assert(Err &&
"Trying to log after takeError().");
1336OS <<
"'" << FileName <<
"': ";
1338OS <<
"line " << *Line <<
": ";
1355// Used by ErrorInfo::classID. 1360 std::unique_ptr<ErrorInfoBase>
E) {
1361assert(
E &&
"Cannot create FileError from Error success value.");
1364 Line = std::move(LineNum);
1368 std::unique_ptr<ErrorInfoBase> Payload;
1370 [&](std::unique_ptr<ErrorInfoBase> EIB) ->
Error {
1371 Payload = std::move(EIB);
1375 std::unique_ptr<FileError>(
new FileError(
F, Line, std::move(Payload))));
1378 std::string FileName;
1379 std::optional<size_t>
Line;
1380 std::unique_ptr<ErrorInfoBase> Err;
1383/// Concatenate a source file path and/or name with an Error. The resulting 1384/// Error is unchecked. 1386return FileError::build(
F, std::optional<size_t>(), std::move(
E));
1389/// Concatenate a source file path and/or name with line number and an Error. 1390/// The resulting Error is unchecked. 1392return FileError::build(
F, std::optional<size_t>(Line), std::move(
E));
1395/// Concatenate a source file path and/or name with a std::error_code 1396/// to form an Error object. 1401/// Concatenate a source file path and/or name with line number and 1402/// std::error_code to form an Error object. 1409/// Helper for check-and-exit error handling. 1411/// For tool use only. NOT FOR USE IN LIBRARY CODE. 1415 /// Create an error on exit helper. 1418 GetExitCode([=](
constError &) {
return DefaultErrorExitCode; }) {}
1420 /// Set the banner string for any errors caught by operator(). 1421voidsetBanner(std::string Banner) { this->Banner = std::move(Banner); }
1423 /// Set the exit-code mapper function. 1425 this->GetExitCode = std::move(GetExitCode);
1428 /// Check Err. If it's in a failure state log the error(s) and exit. 1431 /// Check E. If it's in a success state then return the contained value. If 1432 /// it's in a failure state log the error(s) and exit. 1434 checkError(
E.takeError());
1435return std::move(*
E);
1438 /// Check E. If it's in a success state then return the contained reference. If 1439 /// it's in a failure state log the error(s) and exit. 1441 checkError(
E.takeError());
1446void checkError(
Error Err)
const{
1448int ExitCode = GetExitCode(Err);
1455 std::function<int(
const Error &)> GetExitCode;
1458/// Conversion from Error to LLVMErrorRef for C error bindings. 1460returnreinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1463/// Conversion from LLVMErrorRef to Error for C error bindings. 1465returnError(std::unique_ptr<ErrorInfoBase>(
1469}
// end namespace llvm 1471#endif// LLVM_SUPPORT_ERROR_H static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
std::optional< std::vector< StOtherPiece > > Other
Provides ErrorOr<T> smart pointer.
static LLVMTargetMachineRef wrap(const TargetMachine *P)
static const char * getPtr(const MachOObjectFile &O, size_t Offset, size_t MachOFilesetEntryOffset=0)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This class wraps a std::error_code in a Error.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
ECError(std::error_code EC)
friend Error errorCodeToError(std::error_code)
Helper for converting an std::error_code to a Error.
void setErrorCode(std::error_code EC)
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Helper for Errors used as out-parameters.
ErrorAsOutParameter(Error *Err)
ErrorAsOutParameter(Error &Err)
static bool appliesTo(const ErrorInfoBase &E)
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
static bool appliesTo(const ErrorInfoBase &E)
static bool appliesTo(const ErrorInfoBase &E)
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
static bool appliesTo(const ErrorInfoBase &E)
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Helper for testing applicability of, and applying, handlers for ErrorInfo types.
Base class for error info classes.
virtual ~ErrorInfoBase()=default
virtual std::string message() const
Return the error message as a string.
static const void * classID()
virtual const void * dynamicClassID() const =0
virtual bool isA(const void *const ClassID) const
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
virtual void log(raw_ostream &OS) const =0
Print an error message to an output stream.
Base class for user error types.
bool isA(const void *const ClassID) const override
const void * dynamicClassID() const override
static const void * classID()
Special ErrorInfo subclass representing a list of ErrorInfos.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
friend Error handleErrors(Error E, HandlerTs &&... Handlers)
Pass the ErrorInfo(s) contained in E to their respective handlers.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
friend Error joinErrors(Error, Error)
Concatenate errors.
friend void visitErrors(const Error &E, HandlerT H)
Visit all the ErrorInfo(s) contained in E by passing them to the respective handler,...
Represents either an error or a value T.
Subclass of Error for the sole purpose of identifying the success path in the type system.
Lightweight error class with error context and mandatory checking.
Error(Error &&Other)
Move-construct an error value.
const void * dynamicClassID() const
Returns the dynamic class id of this error, or null if this is a success value.
friend raw_ostream & operator<<(raw_ostream &OS, const Error &E)
static ErrorSuccess success()
Create a success value.
Error(std::unique_ptr< ErrorInfoBase > Payload)
Create an error value.
Error & operator=(const Error &Other)=delete
Error()
Create a success value. Prefer using 'Error::success()' for readability.
Error(const Error &Other)=delete
Error & operator=(Error &&Other)
Move-assign an error value.
bool isA() const
Check whether one error is a subclass of another.
Helper for check-and-exit error handling.
void setBanner(std::string Banner)
Set the banner string for any errors caught by operator().
ExitOnError(std::string Banner="", int DefaultErrorExitCode=1)
Create an error on exit helper.
T operator()(Expected< T > &&E) const
Check E.
T & operator()(Expected< T & > &&E) const
Check E.
void operator()(Error Err) const
Check Err. If it's in a failure state log the error(s) and exit.
void setExitCodeMapper(std::function< int(const Error &)> GetExitCode)
Set the exit-code mapper function.
Helper for Expected<T>s used as out-parameters.
~ExpectedAsOutParameter()
ExpectedAsOutParameter(Expected< T > *ValOrErr)
Tagged union holding either a T or a Error.
const_reference operator*() const
Returns a const reference to the stored T value.
Expected(Expected< OtherT > &&Other, std::enable_if_t<!std::is_convertible_v< OtherT, T > > *=nullptr)
Move construct an Expected<T> value from an Expected<OtherT>, where OtherT isn't convertible to T.
Error moveInto(OtherT &Value, std::enable_if_t< std::is_assignable_v< OtherT &, T && > > *=nullptr) &&
Returns takeError() after moving the held T (if any) into V.
pointer operator->()
Returns a pointer to the stored T value.
reference operator*()
Returns a reference to the stored T value.
Expected(OtherT &&Val, std::enable_if_t< std::is_convertible_v< OtherT, T > > *=nullptr)
Create an Expected<T> success value from the given OtherT value, which must be convertible to T.
~Expected()
Destroy an Expected<T>.
const_reference get() const
Returns a const reference to the stored T value.
bool errorIsA() const
Check that this Expected<T> is an error of type ErrT.
Expected(ErrorSuccess)=delete
Forbid to convert from Error::success() implicitly, this avoids having Expected<T> foo() { return Err...
Expected(Error &&Err)
Create an Expected<T> error value from the given Error.
AlignedCharArrayUnion< storage_type > TStorage
Error takeError()
Take ownership of the stored error.
const_pointer operator->() const
Returns a const pointer to the stored T value.
Expected & operator=(Expected &&Other)
Move-assign from another Expected<T>.
reference get()
Returns a reference to the stored T value.
AlignedCharArrayUnion< error_type > ErrorStorage
std::conditional_t< isRef, wrap, T > storage_type
Expected(Expected &&Other)
Move construct an Expected<T> value.
Expected(Expected< OtherT > &&Other, std::enable_if_t< std::is_convertible_v< OtherT, T > > *=nullptr)
Move construct an Expected<T> value from an Expected<OtherT>, where OtherT must be convertible to T.
This class wraps a filename and another Error.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
std::string messageWithoutFileInfo() const
StringRef getFileName() const
void log(raw_ostream &OS) const override
Print an error message to an output stream.
friend Error createFileError(const Twine &, Error)
Concatenate a source file path and/or name with an Error.
This class wraps a string in an Error.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
const std::string & getMessage() const
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
StringRef - Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
std::string str() const
Return the twine contents as a std::string.
LLVM Value Representation.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
struct LLVMOpaqueError * LLVMErrorRef
Opaque reference to an error instance.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
This is an optimization pass for GlobalISel generic memory operations.
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
void visitErrors(const Error &E, HandlerT H)
Visit all the ErrorInfo(s) contained in E by passing them to the respective handler,...
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
std::optional< T > expectedToStdOptional(Expected< T > &&E)
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
ErrorOr< T > expectedToErrorOr(Expected< T > &&E)
Convert an Expected<T> to an ErrorOr<T>.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
std::optional< T > expectedToOptional(Expected< T > &&E)
Convert an Expected to an Optional without doing anything.
std::string toStringWithoutConsuming(const Error &E)
Like toString(), but does not consume the error.
Error joinErrors(Error E1, Error E2)
Concatenate errors.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Expected< T > handleExpected(Expected< T > ValOrErr, RecoveryFtor &&RecoveryPath, HandlerTs &&... Handlers)
Handle any errors (if present) in an Expected<T>, then try a recovery path.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Error handleErrorImpl(std::unique_ptr< ErrorInfoBase > Payload)
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Attribute unwrap(LLVMAttributeRef Attr)
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
LLVMAttributeRef wrap(Attribute Attr)
const char * toString(DWARFSectionKind Kind)
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
LogicalResult success(bool IsSuccess=true)
Utility function to generate a LogicalResult.
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
void consumeError(Error Err)
Consume a Error without doing anything.
Implement std::hash so that hash_code can be used in STL containers.
A suitably aligned and sized character array member which can hold elements of any type.