[Error] Add FileError helper; upgrade StringError behavior

FileError is meant to encapsulate both an Error and a file name/path. It should be used in cases where an Error occurs deep down the call chain, and we want to return it to the caller along with the file name.

StringError was updated to display the error messages in different ways. These can be:

1. display the error_code message, and convert to the same error_code (ECError behavior)
2. display an arbitrary string, and convert to a provided error_code (current StringError behavior)
3. display both an error_code message and a string, in this order; and convert to the same error_code

These behaviors can be triggered depending on the constructor. The goal is to use StringError as a base class, when a library needs to provide a explicit Error type.

Differential Revision: https://reviews.llvm.org/D50807

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@341064 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Alexandre Ganea
2018-08-30 13:10:42 +00:00
parent 6089d1a3c7
commit 0993f24765
3 changed files with 217 additions and 5 deletions
+22 -2
View File
@@ -19,6 +19,7 @@ namespace {
enum class ErrorErrorCode : int {
MultipleErrors = 1,
FileError,
InconvertibleError
};
@@ -37,6 +38,8 @@ namespace {
return "Inconvertible error value. An error has occurred that could "
"not be converted to a known std::error_code. Please file a "
"bug.";
case ErrorErrorCode::FileError:
return "A file error occurred.";
}
llvm_unreachable("Unhandled error code");
}
@@ -53,6 +56,7 @@ char ErrorInfoBase::ID = 0;
char ErrorList::ID = 0;
char ECError::ID = 0;
char StringError::ID = 0;
char FileError::ID = 0;
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner) {
if (!E)
@@ -75,6 +79,11 @@ std::error_code inconvertibleErrorCode() {
*ErrorErrorCat);
}
std::error_code FileError::convertToErrorCode() const {
return std::error_code(static_cast<int>(ErrorErrorCode::FileError),
*ErrorErrorCat);
}
Error errorCodeToError(std::error_code EC) {
if (!EC)
return Error::success();
@@ -103,10 +112,21 @@ void Error::fatalUncheckedError() const {
}
#endif
StringError::StringError(const Twine &S, std::error_code EC)
StringError::StringError(std::error_code EC, const Twine &S)
: Msg(S.str()), EC(EC) {}
void StringError::log(raw_ostream &OS) const { OS << Msg; }
StringError::StringError(const Twine &S, std::error_code EC)
: Msg(S.str()), EC(EC), PrintMsgOnly(true) {}
void StringError::log(raw_ostream &OS) const {
if (PrintMsgOnly) {
OS << Msg;
} else {
OS << EC.message();
if (!Msg.empty())
OS << (" " + Msg);
}
}
std::error_code StringError::convertToErrorCode() const {
return EC;