[clang-tools-extra] 687e1d7 - [clangd] makeStringError,make_error<StringError> -> error()
Sam McCall via cfe-commits
cfe-commits at lists.llvm.org
Mon Sep 14 02:48:44 PDT 2020
Author: Sam McCall
Date: 2020-09-14T11:48:31+02:00
New Revision: 687e1d7121645d23aa5e919ed4d3c0e57af975cd
URL: https://github.com/llvm/llvm-project/commit/687e1d7121645d23aa5e919ed4d3c0e57af975cd
DIFF: https://github.com/llvm/llvm-project/commit/687e1d7121645d23aa5e919ed4d3c0e57af975cd.diff
LOG: [clangd] makeStringError,make_error<StringError> -> error()
Added:
Modified:
clang-tools-extra/clangd/FindSymbols.cpp
clang-tools-extra/clangd/IncludeFixer.cpp
clang-tools-extra/clangd/JSONTransport.cpp
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/SourceCode.cpp
clang-tools-extra/clangd/URI.cpp
clang-tools-extra/clangd/index/Background.cpp
clang-tools-extra/clangd/index/SymbolID.cpp
clang-tools-extra/clangd/index/YAMLSerialization.cpp
clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
clang-tools-extra/clangd/refactor/Rename.cpp
clang-tools-extra/clangd/refactor/Tweak.cpp
clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp
clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
clang-tools-extra/clangd/refactor/tweaks/ObjCLocalizeStringLiteral.cpp
clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
clang-tools-extra/clangd/refactor/tweaks/SwapIfBranches.cpp
clang-tools-extra/clangd/tool/ClangdMain.cpp
clang-tools-extra/clangd/unittests/TestFS.cpp
clang-tools-extra/clangd/xpc/XPCTransport.cpp
Removed:
################################################################################
diff --git a/clang-tools-extra/clangd/FindSymbols.cpp b/clang-tools-extra/clangd/FindSymbols.cpp
index 247165698825..e37d73103e36 100644
--- a/clang-tools-extra/clangd/FindSymbols.cpp
+++ b/clang-tools-extra/clangd/FindSymbols.cpp
@@ -43,12 +43,9 @@ struct ScoredSymbolGreater {
llvm::Expected<Location> indexToLSPLocation(const SymbolLocation &Loc,
llvm::StringRef TUPath) {
auto Path = URI::resolve(Loc.FileURI, TUPath);
- if (!Path) {
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Could not resolve path for file '{0}': {1}", Loc.FileURI,
- llvm::toString(Path.takeError())),
- llvm::inconvertibleErrorCode());
- }
+ if (!Path)
+ return error("Could not resolve path for file '{0}': {1}", Loc.FileURI,
+ Path.takeError());
Location L;
L.uri = URIForFile::canonicalize(*Path, TUPath);
Position Start, End;
diff --git a/clang-tools-extra/clangd/IncludeFixer.cpp b/clang-tools-extra/clangd/IncludeFixer.cpp
index 945f4eced88c..7704ccb82c0f 100644
--- a/clang-tools-extra/clangd/IncludeFixer.cpp
+++ b/clang-tools-extra/clangd/IncludeFixer.cpp
@@ -153,8 +153,7 @@ std::vector<Fix> IncludeFixer::fixesForSymbols(const SymbolSlab &Syms) const {
return ResolvedInserted.takeError();
auto Spelled = Inserter->calculateIncludePath(*ResolvedInserted, File);
if (!Spelled)
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Header not on include path");
+ return error("Header not on include path");
return std::make_pair(
std::move(*Spelled),
Inserter->shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
diff --git a/clang-tools-extra/clangd/JSONTransport.cpp b/clang-tools-extra/clangd/JSONTransport.cpp
index c591da0db47d..eb5a83882b2b 100644
--- a/clang-tools-extra/clangd/JSONTransport.cpp
+++ b/clang-tools-extra/clangd/JSONTransport.cpp
@@ -12,6 +12,7 @@
#include "support/Shutdown.h"
#include "llvm/Support/Errno.h"
#include "llvm/Support/Error.h"
+#include <system_error>
namespace clang {
namespace clangd {
@@ -100,9 +101,8 @@ class JSONTransport : public Transport {
llvm::Error loop(MessageHandler &Handler) override {
while (!feof(In)) {
if (shutdownRequested())
- return llvm::createStringError(
- std::make_error_code(std::errc::operation_canceled),
- "Got signal, shutting down");
+ return error(std::make_error_code(std::errc::operation_canceled),
+ "Got signal, shutting down");
if (ferror(In))
return llvm::errorCodeToError(
std::error_code(errno, std::system_category()));
diff --git a/clang-tools-extra/clangd/Preamble.cpp b/clang-tools-extra/clangd/Preamble.cpp
index b71afa0b1619..8e1ad7242eb0 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -243,8 +243,7 @@ scanPreamble(llvm::StringRef Contents, const tooling::CompileCommand &Cmd) {
IgnoringDiagConsumer IgnoreDiags;
auto CI = buildCompilerInvocation(PI, IgnoreDiags);
if (!CI)
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "failed to create compiler invocation");
+ return error("failed to create compiler invocation");
CI->getDiagnosticOpts().IgnoreWarnings = true;
auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Contents);
// This means we're scanning (though not preprocessing) the preamble section
@@ -260,14 +259,12 @@ scanPreamble(llvm::StringRef Contents, const tooling::CompileCommand &Cmd) {
// also implies missing resolved paths for includes.
FS.view(llvm::None), IgnoreDiags);
if (Clang->getFrontendOpts().Inputs.empty())
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "compiler instance had no inputs");
+ return error("compiler instance had no inputs");
// We are only interested in main file includes.
Clang->getPreprocessorOpts().SingleFileParseMode = true;
PreprocessOnlyAction Action;
if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]))
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "failed BeginSourceFile");
+ return error("failed BeginSourceFile");
const auto &SM = Clang->getSourceManager();
Preprocessor &PP = Clang->getPreprocessor();
IncludeStructure Includes;
diff --git a/clang-tools-extra/clangd/SourceCode.cpp b/clang-tools-extra/clangd/SourceCode.cpp
index 2b50aea82fb2..0432097b4348 100644
--- a/clang-tools-extra/clangd/SourceCode.cpp
+++ b/clang-tools-extra/clangd/SourceCode.cpp
@@ -175,20 +175,17 @@ size_t lspLength(llvm::StringRef Code) {
llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
bool AllowColumnsBeyondLineLength) {
if (P.line < 0)
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Line value can't be negative ({0})", P.line),
- llvm::errc::invalid_argument);
+ return error(llvm::errc::invalid_argument,
+ "Line value can't be negative ({0})", P.line);
if (P.character < 0)
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Character value can't be negative ({0})", P.character),
- llvm::errc::invalid_argument);
+ return error(llvm::errc::invalid_argument,
+ "Character value can't be negative ({0})", P.character);
size_t StartOfLine = 0;
for (int I = 0; I != P.line; ++I) {
size_t NextNL = Code.find('\n', StartOfLine);
if (NextNL == llvm::StringRef::npos)
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Line value is out of range ({0})", P.line),
- llvm::errc::invalid_argument);
+ return error(llvm::errc::invalid_argument,
+ "Line value is out of range ({0})", P.line);
StartOfLine = NextNL + 1;
}
StringRef Line =
@@ -198,10 +195,9 @@ llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
bool Valid;
size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid);
if (!Valid && !AllowColumnsBeyondLineLength)
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(),
- P.character, P.line),
- llvm::errc::invalid_argument);
+ return error(llvm::errc::invalid_argument,
+ "{0} offset {1} is invalid for line {2}", lspEncoding(),
+ P.character, P.line);
return StartOfLine + ByteInLine;
}
diff --git a/clang-tools-extra/clangd/URI.cpp b/clang-tools-extra/clangd/URI.cpp
index fad93143a30d..f9e8fdc46fa7 100644
--- a/clang-tools-extra/clangd/URI.cpp
+++ b/clang-tools-extra/clangd/URI.cpp
@@ -7,6 +7,7 @@
//===----------------------------------------------------------------------===//
#include "URI.h"
+#include "support/Logger.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
@@ -21,11 +22,6 @@ namespace clang {
namespace clangd {
namespace {
-inline llvm::Error make_string_error(const llvm::Twine &Message) {
- return llvm::make_error<llvm::StringError>(Message,
- llvm::inconvertibleErrorCode());
-}
-
bool isWindowsPath(llvm::StringRef Path) {
return Path.size() > 1 && llvm::isAlpha(Path[0]) && Path[1] == ':';
}
@@ -45,9 +41,9 @@ class FileSystemScheme : public URIScheme {
getAbsolutePath(llvm::StringRef Authority, llvm::StringRef Body,
llvm::StringRef /*HintPath*/) const override {
if (!Body.startswith("/"))
- return make_string_error("File scheme: expect body to be an absolute "
- "path starting with '/': " +
- Body);
+ return error("File scheme: expect body to be an absolute path starting "
+ "with '/': {0}",
+ Body);
llvm::SmallString<128> Path;
if (!Authority.empty()) {
// Windows UNC paths e.g. file://server/share => \\server\share
@@ -89,7 +85,7 @@ findSchemeByName(llvm::StringRef Scheme) {
continue;
return URIScheme.instantiate();
}
- return make_string_error("Can't find scheme: " + Scheme);
+ return error("Can't find scheme: {0}", Scheme);
}
bool shouldEscape(unsigned char C) {
@@ -187,12 +183,11 @@ llvm::Expected<URI> URI::parse(llvm::StringRef OrigUri) {
auto Pos = Uri.find(':');
if (Pos == llvm::StringRef::npos)
- return make_string_error("Scheme must be provided in URI: " + OrigUri);
+ return error("Scheme must be provided in URI: {0}", OrigUri);
auto SchemeStr = Uri.substr(0, Pos);
U.Scheme = percentDecode(SchemeStr);
if (!isValidScheme(U.Scheme))
- return make_string_error(llvm::formatv("Invalid scheme: {0} (decoded: {1})",
- SchemeStr, U.Scheme));
+ return error("Invalid scheme: {0} (decoded: {1})", SchemeStr, U.Scheme);
Uri = Uri.substr(Pos + 1);
if (Uri.consume_front("//")) {
Pos = Uri.find('/');
@@ -217,7 +212,7 @@ llvm::Expected<std::string> URI::resolve(llvm::StringRef FileURI,
llvm::Expected<URI> URI::create(llvm::StringRef AbsolutePath,
llvm::StringRef Scheme) {
if (!llvm::sys::path::is_absolute(AbsolutePath))
- return make_string_error("Not a valid absolute path: " + AbsolutePath);
+ return error("Not a valid absolute path: {0}", AbsolutePath);
auto S = findSchemeByName(Scheme);
if (!S)
return S.takeError();
diff --git a/clang-tools-extra/clangd/index/Background.cpp b/clang-tools-extra/clangd/index/Background.cpp
index 2bac6ec39d30..a1aafeaf31a9 100644
--- a/clang-tools-extra/clangd/index/Background.cpp
+++ b/clang-tools-extra/clangd/index/Background.cpp
@@ -272,15 +272,13 @@ llvm::Error BackgroundIndex::index(tooling::CompileCommand Cmd) {
IgnoreDiagnostics IgnoreDiags;
auto CI = buildCompilerInvocation(Inputs, IgnoreDiags);
if (!CI)
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Couldn't build compiler invocation");
+ return error("Couldn't build compiler invocation");
auto Clang =
prepareCompilerInstance(std::move(CI), /*Preamble=*/nullptr,
std::move(*Buf), std::move(FS), IgnoreDiags);
if (!Clang)
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Couldn't build compiler instance");
+ return error("Couldn't build compiler instance");
SymbolCollector::Options IndexOpts;
// Creates a filter to not collect index results from files with unchanged
@@ -318,8 +316,7 @@ llvm::Error BackgroundIndex::index(tooling::CompileCommand Cmd) {
const FrontendInputFile &Input = Clang->getFrontendOpts().Inputs.front();
if (!Action->BeginSourceFile(*Clang, Input))
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "BeginSourceFile() failed");
+ return error("BeginSourceFile() failed");
if (llvm::Error Err = Action->Execute())
return Err;
diff --git a/clang-tools-extra/clangd/index/SymbolID.cpp b/clang-tools-extra/clangd/index/SymbolID.cpp
index b97103d377ca..2bb3d4f0b6a0 100644
--- a/clang-tools-extra/clangd/index/SymbolID.cpp
+++ b/clang-tools-extra/clangd/index/SymbolID.cpp
@@ -7,6 +7,7 @@
//===----------------------------------------------------------------------===//
#include "SymbolID.h"
+#include "support/Logger.h"
#include "llvm/Support/SHA1.h"
namespace clang {
@@ -34,12 +35,10 @@ std::string SymbolID::str() const { return llvm::toHex(raw()); }
llvm::Expected<SymbolID> SymbolID::fromStr(llvm::StringRef Str) {
if (Str.size() != RawSize * 2)
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Bad ID length");
+ return error("Bad ID length");
for (char C : Str)
if (!llvm::isHexDigit(C))
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Bad hex ID");
+ return error("Bad hex ID");
return fromRaw(llvm::fromHex(Str));
}
diff --git a/clang-tools-extra/clangd/index/YAMLSerialization.cpp b/clang-tools-extra/clangd/index/YAMLSerialization.cpp
index 4f6bd927cc19..d269a3b36eb4 100644
--- a/clang-tools-extra/clangd/index/YAMLSerialization.cpp
+++ b/clang-tools-extra/clangd/index/YAMLSerialization.cpp
@@ -18,6 +18,7 @@
#include "SymbolLocation.h"
#include "SymbolOrigin.h"
#include "dex/Dex.h"
+#include "support/Logger.h"
#include "support/Trace.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
@@ -533,9 +534,7 @@ symbolFromYAML(StringRef YAML, llvm::UniqueStringSaver *Strings) {
clangd::Symbol Deserialized;
llvm::yaml::Input YAMLInput(YAML, Strings);
if (YAMLInput.error())
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Unable to deserialize Symbol from YAML: {0}", YAML),
- llvm::inconvertibleErrorCode());
+ return error("Unable to deserialize Symbol from YAML: {0}", YAML);
YAMLInput >> Deserialized;
return Deserialized;
}
@@ -545,9 +544,7 @@ llvm::Expected<clangd::Ref> refFromYAML(StringRef YAML,
clangd::Ref Deserialized;
llvm::yaml::Input YAMLInput(YAML, Strings);
if (YAMLInput.error())
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Unable to deserialize Symbol from YAML: {0}", YAML),
- llvm::inconvertibleErrorCode());
+ return error("Unable to deserialize Symbol from YAML: {0}", YAML);
YAMLInput >> Deserialized;
return Deserialized;
}
diff --git a/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp b/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
index cfc72ce87be6..839250982a03 100644
--- a/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
+++ b/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
@@ -45,11 +45,6 @@ llvm::Expected<llvm::DenseSet<SymbolID>> getIDs(IDRange IDs) {
return Result;
}
-llvm::Error makeStringError(llvm::StringRef Message) {
- return llvm::make_error<llvm::StringError>(Message,
- llvm::inconvertibleErrorCode());
-}
-
} // namespace
Marshaller::Marshaller(llvm::StringRef RemoteIndexRoot,
@@ -132,7 +127,7 @@ Marshaller::fromProtobuf(const RelationsRequest *Message) {
llvm::Expected<clangd::Symbol> Marshaller::fromProtobuf(const Symbol &Message) {
if (!Message.has_info() || !Message.has_canonical_declaration())
- return makeStringError("Missing info or declaration.");
+ return error("Missing info or declaration.");
clangd::Symbol Result;
auto ID = SymbolID::fromStr(Message.id());
if (!ID)
@@ -170,7 +165,7 @@ llvm::Expected<clangd::Symbol> Marshaller::fromProtobuf(const Symbol &Message) {
llvm::Expected<clangd::Ref> Marshaller::fromProtobuf(const Ref &Message) {
if (!Message.has_location())
- return makeStringError("Missing location.");
+ return error("Missing location.");
clangd::Ref Result;
auto Location = fromProtobuf(Message.location());
if (!Location)
@@ -186,7 +181,7 @@ Marshaller::fromProtobuf(const Relation &Message) {
if (!SubjectID)
return SubjectID.takeError();
if (!Message.has_object())
- return makeStringError("Missing Object.");
+ return error("Missing Object.");
auto Object = fromProtobuf(Message.object());
if (!Object)
return Object.takeError();
@@ -304,10 +299,9 @@ Marshaller::relativePathToURI(llvm::StringRef RelativePath) {
assert(RelativePath == llvm::sys::path::convert_to_slash(
RelativePath, llvm::sys::path::Style::posix));
if (RelativePath.empty())
- return makeStringError("Empty relative path.");
+ return error("Empty relative path.");
if (llvm::sys::path::is_absolute(RelativePath))
- return makeStringError(
- llvm::formatv("RelativePath '{0}' is absolute.", RelativePath).str());
+ return error("RelativePath '{0}' is absolute.", RelativePath);
llvm::SmallString<256> FullPath = llvm::StringRef(*LocalIndexRoot);
llvm::sys::path::append(FullPath, RelativePath);
auto Result = URI::createFile(FullPath);
@@ -320,16 +314,11 @@ llvm::Expected<std::string> Marshaller::uriToRelativePath(llvm::StringRef URI) {
if (!ParsedURI)
return ParsedURI.takeError();
if (ParsedURI->scheme() != "file")
- return makeStringError(
- llvm::formatv("Can not use URI schemes other than file, given: '{0}'.",
- URI)
- .str());
+ return error("Can not use URI schemes other than file, given: '{0}'.", URI);
llvm::SmallString<256> Result = ParsedURI->body();
if (!llvm::sys::path::replace_path_prefix(Result, *RemoteIndexRoot, ""))
- return makeStringError(
- llvm::formatv("File path '{0}' doesn't start with '{1}'.", Result.str(),
- *RemoteIndexRoot)
- .str());
+ return error("File path '{0}' doesn't start with '{1}'.", Result.str(),
+ *RemoteIndexRoot);
// Make sure the result has UNIX slashes.
return llvm::sys::path::convert_to_slash(Result,
llvm::sys::path::Style::posix);
diff --git a/clang-tools-extra/clangd/refactor/Rename.cpp b/clang-tools-extra/clangd/refactor/Rename.cpp
index ea75de6e86ea..2744caa58648 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -213,9 +213,7 @@ llvm::Error makeError(ReasonToReject Reason) {
}
llvm_unreachable("unhandled reason kind");
};
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Cannot rename symbol: {0}", Message(Reason)),
- llvm::inconvertibleErrorCode());
+ return error("Cannot rename symbol: {0}", Message(Reason));
}
// Return all rename occurrences in the main file.
@@ -319,16 +317,11 @@ findOccurrencesOutsideFile(const NamedDecl &RenameDecl,
});
if (AffectedFiles.size() >= MaxLimitFiles)
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("The number of affected files exceeds the max limit {0}",
- MaxLimitFiles),
- llvm::inconvertibleErrorCode());
- if (HasMore) {
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("The symbol {0} has too many occurrences",
- RenameDecl.getQualifiedNameAsString()),
- llvm::inconvertibleErrorCode());
- }
+ return error("The number of affected files exceeds the max limit {0}",
+ MaxLimitFiles);
+ if (HasMore)
+ return error("The symbol {0} has too many occurrences",
+ RenameDecl.getQualifiedNameAsString());
// Sort and deduplicate the results, in case that index returns duplications.
for (auto &FileAndOccurrences : AffectedFiles) {
auto &Ranges = FileAndOccurrences.getValue();
@@ -379,20 +372,15 @@ llvm::Expected<FileEdits> renameOutsideFile(
// Our heuristics fails to adjust rename ranges to the current state of
// the file, it is most likely the index is stale, so we give up the
// entire rename.
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Index results don't match the content of file {0} "
- "(the index may be stale)",
- FilePath),
- llvm::inconvertibleErrorCode());
+ return error("Index results don't match the content of file {0} "
+ "(the index may be stale)",
+ FilePath);
}
auto RenameEdit =
buildRenameEdit(FilePath, *AffectedFileCode, *RenameRanges, NewName);
- if (!RenameEdit) {
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("fail to build rename edit for file {0}: {1}", FilePath,
- llvm::toString(RenameEdit.takeError())),
- llvm::inconvertibleErrorCode());
- }
+ if (!RenameEdit)
+ return error("failed to rename in file {0}: {1}", FilePath,
+ RenameEdit.takeError());
if (!RenameEdit->Replacements.empty())
Results.insert({FilePath, std::move(*RenameEdit)});
}
@@ -455,14 +443,10 @@ llvm::Expected<FileEdits> rename(const RenameInputs &RInputs) {
auto Content =
SM.getFileManager().getVirtualFileSystem().getBufferForFile(AbsPath);
if (!Content)
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- llvm::formatv("Fail to open file {0}: {1}", AbsPath,
- Content.getError().message()));
+ return error("Fail to open file {0}: {1}", AbsPath,
+ Content.getError().message());
if (!*Content)
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- llvm::formatv("Got no buffer for file {0}", AbsPath));
+ return error("Got no buffer for file {0}", AbsPath);
return (*Content)->getBuffer().str();
};
@@ -559,10 +543,8 @@ llvm::Expected<Edit> buildRenameEdit(llvm::StringRef AbsFilePath,
auto ShiftedOffset =
positionToOffset(InitialCode.substr(LastOffset), Shifted);
if (!ShiftedOffset)
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("fail to convert the position {0} to offset ({1})", P,
- llvm::toString(ShiftedOffset.takeError())),
- llvm::inconvertibleErrorCode());
+ return error("fail to convert the position {0} to offset ({1})", P,
+ ShiftedOffset.takeError());
LastPos = P;
LastOffset += *ShiftedOffset;
return LastOffset;
diff --git a/clang-tools-extra/clangd/refactor/Tweak.cpp b/clang-tools-extra/clangd/refactor/Tweak.cpp
index b1f4dcd69af6..34b5b2b544df 100644
--- a/clang-tools-extra/clangd/refactor/Tweak.cpp
+++ b/clang-tools-extra/clangd/refactor/Tweak.cpp
@@ -80,12 +80,10 @@ llvm::Expected<std::unique_ptr<Tweak>> prepareTweak(StringRef ID,
TweakRegistry::entries(),
[ID](const TweakRegistry::entry &E) { return E.getName() == ID; });
if (It == TweakRegistry::end())
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "id of the tweak is invalid");
+ return error("tweak ID {0} is invalid", ID);
std::unique_ptr<Tweak> T = It->instantiate();
if (!T->prepare(S))
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "failed to prepare() a check");
+ return error("failed to prepare() tweak {0}", ID);
return std::move(T);
}
@@ -95,10 +93,8 @@ Tweak::Effect::fileEdit(const SourceManager &SM, FileID FID,
Edit Ed(SM.getBufferData(FID), std::move(Replacements));
if (auto FilePath = getCanonicalPath(SM.getFileEntryForID(FID), SM))
return std::make_pair(*FilePath, std::move(Ed));
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- "Failed to get absolute path for edited file: " +
- SM.getFileEntryForID(FID)->getName());
+ return error("Failed to get absolute path for edited file: {0}",
+ SM.getFileEntryForID(FID)->getName());
}
llvm::Expected<Tweak::Effect>
diff --git a/clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp b/clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp
index e4900041671a..d5e6e12b31aa 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp
@@ -169,8 +169,7 @@ findInsertionPoint(const Tweak::Selection &Inputs,
return Tok.kind() == tok::l_brace;
});
if (Tok == Toks.end() || Tok->endLocation().isInvalid()) {
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Namespace with no {");
+ return error("Namespace with no {");
}
if (!Tok->endLocation().isMacroID()) {
InsertionPointData Out;
@@ -183,8 +182,7 @@ findInsertionPoint(const Tweak::Selection &Inputs,
// top level decl.
auto TLDs = Inputs.AST->getLocalTopLevelDecls();
if (TLDs.empty()) {
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Cannot find place to insert \"using\"");
+ return error("Cannot find place to insert \"using\"");
}
InsertionPointData Out;
Out.Loc = SM.getExpansionLoc(TLDs[0]->getBeginLoc());
@@ -272,9 +270,7 @@ Expected<Tweak::Effect> AddUsing::apply(const Selection &Inputs) {
auto SpelledTokens = TB.spelledForExpanded(
TB.expandedTokens(QualifierToRemove.getSourceRange()));
if (!SpelledTokens) {
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- "Could not determine length of the qualifier");
+ return error("Could not determine length of the qualifier");
}
unsigned Length =
syntax::Token::range(SM, SpelledTokens->front(), SpelledTokens->back())
diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
index 698d2a406811..cdd5f9c6595b 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
@@ -205,18 +205,15 @@ llvm::Expected<std::string> qualifyAllDecls(const FunctionDecl *FD,
}
});
- if (HadErrors) {
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- "define inline: Failed to compute qualifiers see logs for details.");
- }
+ if (HadErrors)
+ return error(
+ "define inline: Failed to compute qualifiers. See logs for details.");
// Get new begin and end positions for the qualified body.
auto OrigBodyRange = toHalfOpenFileRange(
SM, FD->getASTContext().getLangOpts(), FD->getBody()->getSourceRange());
if (!OrigBodyRange)
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Couldn't get range func body.");
+ return error("Couldn't get range func body.");
unsigned BodyBegin = SM.getFileOffset(OrigBodyRange->getBegin());
unsigned BodyEnd = Replacements.getShiftedCodePosition(
@@ -311,9 +308,7 @@ renameParameters(const FunctionDecl *Dest, const FunctionDecl *Source) {
ReplaceRange = Lexer::makeFileCharRange(ReplaceRange, SM, LangOpts);
// Bail out if we need to replace macro bodies.
if (ReplaceRange.isInvalid()) {
- auto Err = llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- "Cant rename parameter inside macro body.");
+ auto Err = error("Cant rename parameter inside macro body.");
elog("define inline: {0}", Err);
return std::move(Err);
}
@@ -450,11 +445,8 @@ class DefineInline : public Tweak {
const auto &SM = AST.getSourceManager();
auto Semicolon = getSemicolonForDecl(Target);
- if (!Semicolon) {
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- "Couldn't find semicolon for target declaration.");
- }
+ if (!Semicolon)
+ return error("Couldn't find semicolon for target declaration.");
auto AddInlineIfNecessary = addInlineIfInHeader(Target);
auto ParamReplacements = renameParameters(Target, Source);
@@ -479,10 +471,8 @@ class DefineInline : public Tweak {
SM.getExpansionRange(CharSourceRange::getCharRange(getBeginLoc(Source),
Source->getEndLoc()))
.getAsRange());
- if (!DefRange) {
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Couldn't get range for the source.");
- }
+ if (!DefRange)
+ return error("Couldn't get range for the source.");
unsigned int SourceLen = SM.getFileOffset(DefRange->getEnd()) -
SM.getFileOffset(DefRange->getBegin());
const tooling::Replacement DeleteFuncBody(SM, DefRange->getBegin(),
diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
index 66d9c4c36b12..ed4d0cc46269 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -120,8 +120,7 @@ getFunctionSourceAfterReplacements(const FunctionDecl *FD,
auto OrigFuncRange = toHalfOpenFileRange(
SM, FD->getASTContext().getLangOpts(), FD->getSourceRange());
if (!OrigFuncRange)
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Couldn't get range for function.");
+ return error("Couldn't get range for function.");
assert(!FD->getDescribedFunctionTemplate() &&
"Define out-of-line doesn't apply to function templates.");
@@ -151,9 +150,7 @@ getFunctionSourceCode(const FunctionDecl *FD, llvm::StringRef TargetNamespace,
auto &SM = AST.getSourceManager();
auto TargetContext = findContextForNS(TargetNamespace, FD->getDeclContext());
if (!TargetContext)
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- "define outline: couldn't find a context for target");
+ return error("define outline: couldn't find a context for target");
llvm::Error Errors = llvm::Error::success();
tooling::Replacements DeclarationCleanups;
@@ -219,12 +216,9 @@ getFunctionSourceCode(const FunctionDecl *FD, llvm::StringRef TargetNamespace,
assert(A->getLocation().isValid());
if (!AttrTokens || AttrTokens->empty()) {
Errors = llvm::joinErrors(
- std::move(Errors),
- llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- llvm::StringRef("define outline: Can't move out of line as "
- "function has a macro `") +
- A->getSpelling() + "` specifier."));
+ std::move(Errors), error("define outline: Can't move out of line as "
+ "function has a macro `{0}` specifier.",
+ A->getSpelling()));
return;
}
CharSourceRange DelRange =
@@ -248,10 +242,8 @@ getFunctionSourceCode(const FunctionDecl *FD, llvm::StringRef TargetNamespace,
if (!Spelling) {
Errors = llvm::joinErrors(
std::move(Errors),
- llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- llvm::formatv("define outline: couldn't remove `{0}` keyword.",
- tok::getKeywordSpelling(Kind))));
+ error("define outline: couldn't remove `{0}` keyword.",
+ tok::getKeywordSpelling(Kind)));
break;
}
CharSourceRange DelRange =
@@ -264,11 +256,8 @@ getFunctionSourceCode(const FunctionDecl *FD, llvm::StringRef TargetNamespace,
if (!FoundAny) {
Errors = llvm::joinErrors(
std::move(Errors),
- llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- llvm::formatv(
- "define outline: couldn't find `{0}` keyword to remove.",
- tok::getKeywordSpelling(Kind))));
+ error("define outline: couldn't find `{0}` keyword to remove.",
+ tok::getKeywordSpelling(Kind)));
}
};
@@ -411,15 +400,11 @@ class DefineOutline : public Tweak {
auto MainFileName =
getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM);
if (!MainFileName)
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- "Couldn't get absolute path for mainfile.");
+ return error("Couldn't get absolute path for main file.");
auto CCFile = getSourceFile(*MainFileName, Sel);
if (!CCFile)
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- "Couldn't find a suitable implementation file.");
+ return error("Couldn't find a suitable implementation file.");
auto &FS =
Sel.AST->getSourceManager().getFileManager().getVirtualFileSystem();
@@ -427,8 +412,7 @@ class DefineOutline : public Tweak {
// FIXME: Maybe we should consider creating the implementation file if it
// doesn't exist?
if (!Buffer)
- return llvm::createStringError(Buffer.getError(),
- Buffer.getError().message());
+ return llvm::errorCodeToError(Buffer.getError());
auto Contents = Buffer->get()->getBuffer();
auto InsertionPoint = getInsertionPoint(
Contents, Source->getQualifiedNameAsString(), Sel.AST->getLangOpts());
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
index d2dfc4a537d4..f9db50d934b0 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
@@ -45,11 +45,6 @@ class ExpandAutoType : public Tweak {
private:
/// Cache the AutoTypeLoc, so that we do not need to search twice.
llvm::Optional<clang::AutoTypeLoc> CachedLocation;
-
- /// Create an error message with filename and line number in it
- llvm::Error createErrorMessage(const std::string& Message,
- const Selection &Inputs);
-
};
REGISTER_TWEAK(ExpandAutoType)
@@ -78,21 +73,19 @@ Expected<Tweak::Effect> ExpandAutoType::apply(const Selection& Inputs) {
// if we can't resolve the type, return an error message
if (DeducedType == llvm::None)
- return createErrorMessage("Could not deduce type for 'auto' type", Inputs);
+ return error("Could not deduce type for 'auto' type");
// if it's a lambda expression, return an error message
if (isa<RecordType>(*DeducedType) &&
dyn_cast<RecordType>(*DeducedType)->getDecl()->isLambda()) {
- return createErrorMessage("Could not expand type of lambda expression",
- Inputs);
+ return error("Could not expand type of lambda expression");
}
// if it's a function expression, return an error message
// naively replacing 'auto' with the type will break declarations.
// FIXME: there are other types that have similar problems
if (DeducedType->getTypePtr()->isFunctionPointerType()) {
- return createErrorMessage("Could not expand type of function pointer",
- Inputs);
+ return error("Could not expand type of function pointer");
}
std::string PrettyTypeName = printType(*DeducedType,
@@ -105,18 +98,6 @@ Expected<Tweak::Effect> ExpandAutoType::apply(const Selection& Inputs) {
return Effect::mainFileEdit(SrcMgr, tooling::Replacements(Expansion));
}
-llvm::Error ExpandAutoType::createErrorMessage(const std::string& Message,
- const Selection& Inputs) {
- auto &SrcMgr = Inputs.AST->getSourceManager();
- std::string ErrorMessage =
- Message + ": " +
- SrcMgr.getFilename(Inputs.Cursor).str() + " Line " +
- std::to_string(SrcMgr.getExpansionLineNumber(Inputs.Cursor));
-
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- ErrorMessage.c_str());
-}
-
} // namespace
} // namespace clangd
} // namespace clang
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
index d4c723e02eeb..6ee5aee37f51 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -625,9 +625,8 @@ llvm::Expected<NewFunction> getExtractedFunction(ExtractionZone &ExtZone,
CapturedZoneInfo CapturedInfo = captureZoneInfo(ExtZone);
// Bail out if any break of continue exists
if (CapturedInfo.BrokenControlFlow)
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- +"Cannot extract break/continue without "
- "corresponding loop/switch statement.");
+ return error("Cannot extract break/continue without corresponding "
+ "loop/switch statement.");
NewFunction ExtractedFunc(getSemicolonPolicy(ExtZone, SM, LangOpts));
ExtractedFunc.BodyRange = ExtZone.ZoneRange;
ExtractedFunc.InsertionPoint = ExtZone.getInsertionPoint();
@@ -637,8 +636,7 @@ llvm::Expected<NewFunction> getExtractedFunction(ExtractionZone &ExtZone,
if (!createParameters(ExtractedFunc, CapturedInfo) ||
!generateReturnProperties(ExtractedFunc, *ExtZone.EnclosingFunction,
CapturedInfo))
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- +"Too complex to extract.");
+ return error("Too complex to extract.");
return ExtractedFunc;
}
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ObjCLocalizeStringLiteral.cpp b/clang-tools-extra/clangd/refactor/tweaks/ObjCLocalizeStringLiteral.cpp
index 2534cf562daa..894f018aa796 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ObjCLocalizeStringLiteral.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ObjCLocalizeStringLiteral.cpp
@@ -68,8 +68,7 @@ ObjCLocalizeStringLiteral::apply(const Selection &Inputs) {
const auto &TB = AST->getTokens();
auto Toks = TB.spelledForExpanded(TB.expandedTokens(Str->getSourceRange()));
if (!Toks || Toks->empty())
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "Failed to find tokens to replace.");
+ return error("Failed to find tokens to replace.");
// Insert `NSLocalizedString(` before the literal.
auto Reps = tooling::Replacements(tooling::Replacement(
SM, Toks->front().location(), 0, "NSLocalizedString("));
diff --git a/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp b/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
index e054e33c046a..9d1a9f12567c 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
@@ -10,6 +10,7 @@
#include "Selection.h"
#include "SourceCode.h"
#include "refactor/Tweak.h"
+#include "support/Logger.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
@@ -73,8 +74,7 @@ removeUsingDirective(ASTContext &Ctx, const UsingDirectiveDecl *D) {
llvm::Optional<Token> NextTok =
Lexer::findNextToken(D->getEndLoc(), SM, Ctx.getLangOpts());
if (!NextTok || NextTok->isNot(tok::semi))
- return llvm::createStringError(llvm::inconvertibleErrorCode(),
- "no semicolon after using-directive");
+ return error("no semicolon after using-directive");
// FIXME: removing the semicolon may be invalid in some obscure cases, e.g.
// if (x) using namespace std; else using namespace bar;
return tooling::Replacement(
diff --git a/clang-tools-extra/clangd/refactor/tweaks/SwapIfBranches.cpp b/clang-tools-extra/clangd/refactor/tweaks/SwapIfBranches.cpp
index d6966e699fdb..d5299f014cc7 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/SwapIfBranches.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/SwapIfBranches.cpp
@@ -69,15 +69,11 @@ Expected<Tweak::Effect> SwapIfBranches::apply(const Selection &Inputs) {
auto ThenRng = toHalfOpenFileRange(SrcMgr, Ctx.getLangOpts(),
If->getThen()->getSourceRange());
if (!ThenRng)
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- "Could not obtain range of the 'then' branch. Macros?");
+ return error("Could not obtain range of the 'then' branch. Macros?");
auto ElseRng = toHalfOpenFileRange(SrcMgr, Ctx.getLangOpts(),
If->getElse()->getSourceRange());
if (!ElseRng)
- return llvm::createStringError(
- llvm::inconvertibleErrorCode(),
- "Could not obtain range of the 'else' branch. Macros?");
+ return error("Could not obtain range of the 'else' branch. Macros?");
auto ThenCode = toSourceCode(SrcMgr, *ThenRng);
auto ElseCode = toSourceCode(SrcMgr, *ElseRng);
diff --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index dcbaa3523822..cf74ded93632 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -484,9 +484,9 @@ class TestScheme : public URIScheme {
// Still require "/" in body to mimic file scheme, as we want lengths of an
// equivalent URI in both schemes to be the same.
if (!Body.startswith("/"))
- return llvm::make_error<llvm::StringError>(
- "Expect URI body to be an absolute path starting with '/': " + Body,
- llvm::inconvertibleErrorCode());
+ return error(
+ "Expect URI body to be an absolute path starting with '/': {0}",
+ Body);
Body = Body.ltrim('/');
llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
path::native(Path);
@@ -497,11 +497,9 @@ class TestScheme : public URIScheme {
llvm::Expected<URI>
uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
llvm::StringRef Body = AbsolutePath;
- if (!Body.consume_front(TestScheme::TestDir)) {
- return llvm::make_error<llvm::StringError>(
- "Path " + AbsolutePath + " doesn't start with root " + TestDir,
- llvm::inconvertibleErrorCode());
- }
+ if (!Body.consume_front(TestScheme::TestDir))
+ return error("Path {0} doesn't start with root {1}", AbsolutePath,
+ TestDir);
return URI("test", /*Authority=*/"",
llvm::sys::path::convert_to_slash(Body));
diff --git a/clang-tools-extra/clangd/unittests/TestFS.cpp b/clang-tools-extra/clangd/unittests/TestFS.cpp
index 3b2fbc142a28..ba4010cb4581 100644
--- a/clang-tools-extra/clangd/unittests/TestFS.cpp
+++ b/clang-tools-extra/clangd/unittests/TestFS.cpp
@@ -100,13 +100,9 @@ class TestScheme : public URIScheme {
getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
llvm::StringRef HintPath) const override {
if (!HintPath.startswith(testRoot()))
- return llvm::make_error<llvm::StringError>(
- "Hint path doesn't start with test root: " + HintPath,
- llvm::inconvertibleErrorCode());
+ return error("Hint path doesn't start with test root: {0}", HintPath);
if (!Body.consume_front("/"))
- return llvm::make_error<llvm::StringError>(
- "Body of an unittest: URI must start with '/'",
- llvm::inconvertibleErrorCode());
+ return error("Body of an unittest: URI must start with '/'");
llvm::SmallString<16> Path(Body.begin(), Body.end());
llvm::sys::path::native(Path);
return testPath(Path);
@@ -116,9 +112,7 @@ class TestScheme : public URIScheme {
uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
llvm::StringRef Body = AbsolutePath;
if (!Body.consume_front(testRoot()))
- return llvm::make_error<llvm::StringError>(
- AbsolutePath + "does not start with " + testRoot(),
- llvm::inconvertibleErrorCode());
+ return error("{0} does not start with {1}", AbsolutePath, testRoot());
return URI(Scheme, /*Authority=*/"",
llvm::sys::path::convert_to_slash(Body));
diff --git a/clang-tools-extra/clangd/xpc/XPCTransport.cpp b/clang-tools-extra/clangd/xpc/XPCTransport.cpp
index 50eacf2115ee..9eb083953b96 100644
--- a/clang-tools-extra/clangd/xpc/XPCTransport.cpp
+++ b/clang-tools-extra/clangd/xpc/XPCTransport.cpp
@@ -41,7 +41,7 @@ Error decodeError(const json::Object &O) {
std::string(O.getString("message").getValueOr("Unspecified error"));
if (auto Code = O.getInteger("code"))
return make_error<LSPError>(std::move(Msg), ErrorCode(*Code));
- return make_error<StringError>(std::move(Msg), inconvertibleErrorCode());
+ return error("{0}", Msg);
}
// C "closure" for XPCTransport::loop() method
More information about the cfe-commits
mailing list