summaryrefslogtreecommitdiff
path: root/clang-tools-extra/clangd
diff options
context:
space:
mode:
authorIlya Biryukov <ibiryukov@google.com>2019-01-07 15:45:19 +0000
committerIlya Biryukov <ibiryukov@google.com>2019-01-07 15:45:19 +0000
commit3bdd3dd087b85026ab0094641a3b0e20935909ed (patch)
tree927dbfe5191a3e3f8dfc761fe40b01887f571d15 /clang-tools-extra/clangd
parent2719a805361b26c38774b81355f70aea9e75b8a2 (diff)
[clangd] Remove 'using namespace llvm' from .cpp files. NFC
The new guideline is to qualify with 'llvm::' explicitly both in '.h' and '.cpp' files. This simplifies moving the code between header and source files and is easier to keep consistent.
Diffstat (limited to 'clang-tools-extra/clangd')
-rw-r--r--clang-tools-extra/clangd/AST.cpp18
-rw-r--r--clang-tools-extra/clangd/ClangdLSPServer.cpp190
-rw-r--r--clang-tools-extra/clangd/ClangdServer.cpp98
-rw-r--r--clang-tools-extra/clangd/ClangdUnit.cpp54
-rw-r--r--clang-tools-extra/clangd/CodeComplete.cpp138
-rw-r--r--clang-tools-extra/clangd/CodeCompletionStrings.cpp13
-rw-r--r--clang-tools-extra/clangd/Compiler.cpp19
-rw-r--r--clang-tools-extra/clangd/Diagnostics.cpp41
-rw-r--r--clang-tools-extra/clangd/DraftStore.cpp32
-rw-r--r--clang-tools-extra/clangd/ExpectedTypes.cpp14
-rw-r--r--clang-tools-extra/clangd/FS.cpp44
-rw-r--r--clang-tools-extra/clangd/FSProvider.cpp24
-rw-r--r--clang-tools-extra/clangd/FileDistance.cpp71
-rw-r--r--clang-tools-extra/clangd/FindSymbols.cpp9
-rw-r--r--clang-tools-extra/clangd/FuzzyMatch.cpp46
-rw-r--r--clang-tools-extra/clangd/GlobalCompilationDatabase.cpp17
-rw-r--r--clang-tools-extra/clangd/Headers.cpp32
-rw-r--r--clang-tools-extra/clangd/JSONTransport.cpp118
-rw-r--r--clang-tools-extra/clangd/Logger.cpp14
-rw-r--r--clang-tools-extra/clangd/Protocol.cpp309
-rw-r--r--clang-tools-extra/clangd/Quality.cpp88
-rw-r--r--clang-tools-extra/clangd/RIFF.cpp21
-rw-r--r--clang-tools-extra/clangd/SourceCode.cpp92
-rw-r--r--clang-tools-extra/clangd/TUScheduler.cpp86
-rw-r--r--clang-tools-extra/clangd/Threading.cpp11
-rw-r--r--clang-tools-extra/clangd/Trace.cpp93
-rw-r--r--clang-tools-extra/clangd/URI.cpp89
-rw-r--r--clang-tools-extra/clangd/XRefs.cpp52
-rw-r--r--clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp18
-rw-r--r--clang-tools-extra/clangd/index/Background.cpp61
-rw-r--r--clang-tools-extra/clangd/index/CanonicalIncludes.cpp32
-rw-r--r--clang-tools-extra/clangd/index/FileIndex.cpp17
-rw-r--r--clang-tools-extra/clangd/index/Index.cpp45
-rw-r--r--clang-tools-extra/clangd/index/IndexAction.cpp13
-rw-r--r--clang-tools-extra/clangd/index/MemIndex.cpp12
-rw-r--r--clang-tools-extra/clangd/index/Merge.cpp17
-rw-r--r--clang-tools-extra/clangd/index/Serialization.cpp138
-rw-r--r--clang-tools-extra/clangd/index/SymbolCollector.cpp33
-rw-r--r--clang-tools-extra/clangd/index/SymbolID.cpp28
-rw-r--r--clang-tools-extra/clangd/index/YAMLSerialization.cpp35
-rw-r--r--clang-tools-extra/clangd/index/dex/Dex.cpp33
-rw-r--r--clang-tools-extra/clangd/index/dex/Iterator.cpp17
-rw-r--r--clang-tools-extra/clangd/index/dex/PostingList.cpp29
-rw-r--r--clang-tools-extra/clangd/index/dex/Trigram.cpp13
-rw-r--r--clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp161
-rw-r--r--clang-tools-extra/clangd/indexer/IndexerMain.cpp27
-rw-r--r--clang-tools-extra/clangd/tool/ClangdMain.cpp315
47 files changed, 1479 insertions, 1398 deletions
diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 7c270ee0d86..a185a6d8270 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -18,7 +18,6 @@
#include "llvm/Support/Casting.h"
#include "llvm/Support/ScopedPrinter.h"
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -35,8 +34,8 @@ bool isSpelledInSourceCode(const Decl *D) {
// macros, we should use the location where the whole definition occurs.
if (Loc.isMacroID()) {
std::string PrintLoc = SM.getSpellingLoc(Loc).printToString(SM);
- if (StringRef(PrintLoc).startswith("<scratch") ||
- StringRef(PrintLoc).startswith("<command line>"))
+ if (llvm::StringRef(PrintLoc).startswith("<scratch") ||
+ llvm::StringRef(PrintLoc).startswith("<command line>"))
return false;
}
return true;
@@ -54,7 +53,7 @@ SourceLocation findNameLoc(const clang::Decl *D) {
std::string printQualifiedName(const NamedDecl &ND) {
std::string QName;
- raw_string_ostream OS(QName);
+ llvm::raw_string_ostream OS(QName);
PrintingPolicy Policy(ND.getASTContext().getLangOpts());
// Note that inline namespaces are treated as transparent scopes. This
// reflects the way they're most commonly used for lookup. Ideally we'd
@@ -115,18 +114,19 @@ std::string printNamespaceScope(const DeclContext &DC) {
return "";
}
-Optional<SymbolID> getSymbolID(const Decl *D) {
- SmallString<128> USR;
+llvm::Optional<SymbolID> getSymbolID(const Decl *D) {
+ llvm::SmallString<128> USR;
if (index::generateUSRForDecl(D, USR))
return None;
return SymbolID(USR);
}
-Optional<SymbolID> getSymbolID(const IdentifierInfo &II, const MacroInfo *MI,
- const SourceManager &SM) {
+llvm::Optional<SymbolID> getSymbolID(const IdentifierInfo &II,
+ const MacroInfo *MI,
+ const SourceManager &SM) {
if (MI == nullptr)
return None;
- SmallString<128> USR;
+ llvm::SmallString<128> USR;
if (index::generateUSRForMacro(II.getName(), MI->getDefinitionLoc(), SM, USR))
return None;
return SymbolID(USR);
diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index 08a0810d17d..e84adebac44 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -18,7 +18,6 @@
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -69,7 +68,7 @@ class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
public:
MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
- bool onNotify(StringRef Method, json::Value Params) override {
+ bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
log("<-- {0}", Method);
if (Method == "exit")
return false;
@@ -84,7 +83,8 @@ public:
return true;
}
- bool onCall(StringRef Method, json::Value Params, json::Value ID) override {
+ bool onCall(llvm::StringRef Method, llvm::json::Value Params,
+ llvm::json::Value ID) override {
// Calls can be canceled by the client. Add cancellation context.
WithContext WithCancel(cancelableRequestContext(ID));
trace::Span Tracer(Method);
@@ -93,22 +93,23 @@ public:
log("<-- {0}({1})", Method, ID);
if (!Server.Server && Method != "initialize") {
elog("Call {0} before initialization.", Method);
- Reply(make_error<LSPError>("server not initialized",
- ErrorCode::ServerNotInitialized));
+ Reply(llvm::make_error<LSPError>("server not initialized",
+ ErrorCode::ServerNotInitialized));
} else if (auto Handler = Calls.lookup(Method))
Handler(std::move(Params), std::move(Reply));
else
- Reply(
- make_error<LSPError>("method not found", ErrorCode::MethodNotFound));
+ Reply(llvm::make_error<LSPError>("method not found",
+ ErrorCode::MethodNotFound));
return true;
}
- bool onReply(json::Value ID, Expected<json::Value> Result) override {
+ bool onReply(llvm::json::Value ID,
+ llvm::Expected<llvm::json::Value> Result) override {
// We ignore replies, just log them.
if (Result)
log("<-- reply({0})", ID);
else
- log("<-- reply({0}) error: {1}", ID, toString(Result.takeError()));
+ log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
return true;
}
@@ -116,15 +117,15 @@ public:
template <typename Param, typename Result>
void bind(const char *Method,
void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
- Calls[Method] = [Method, Handler, this](json::Value RawParams,
+ Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
ReplyOnce Reply) {
Param P;
if (fromJSON(RawParams, P)) {
(Server.*Handler)(P, std::move(Reply));
} else {
elog("Failed to decode {0} request.", Method);
- Reply(make_error<LSPError>("failed to decode request",
- ErrorCode::InvalidRequest));
+ Reply(llvm::make_error<LSPError>("failed to decode request",
+ ErrorCode::InvalidRequest));
}
};
}
@@ -133,7 +134,8 @@ public:
template <typename Param>
void bind(const char *Method,
void (ClangdLSPServer::*Handler)(const Param &)) {
- Notifications[Method] = [Method, Handler, this](json::Value RawParams) {
+ Notifications[Method] = [Method, Handler,
+ this](llvm::json::Value RawParams) {
Param P;
if (!fromJSON(RawParams, P)) {
elog("Failed to decode {0} request.", Method);
@@ -154,14 +156,14 @@ private:
class ReplyOnce {
std::atomic<bool> Replied = {false};
std::chrono::steady_clock::time_point Start;
- json::Value ID;
+ llvm::json::Value ID;
std::string Method;
ClangdLSPServer *Server; // Null when moved-from.
- json::Object *TraceArgs;
+ llvm::json::Object *TraceArgs;
public:
- ReplyOnce(const json::Value &ID, StringRef Method, ClangdLSPServer *Server,
- json::Object *TraceArgs)
+ ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
+ ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
: Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
Server(Server), TraceArgs(TraceArgs) {
assert(Server);
@@ -180,12 +182,12 @@ private:
if (Server && !Replied) {
elog("No reply to message {0}({1})", Method, ID);
assert(false && "must reply to all calls!");
- (*this)(make_error<LSPError>("server failed to reply",
- ErrorCode::InternalError));
+ (*this)(llvm::make_error<LSPError>("server failed to reply",
+ ErrorCode::InternalError));
}
}
- void operator()(Expected<json::Value> Reply) {
+ void operator()(llvm::Expected<llvm::json::Value> Reply) {
assert(Server && "moved-from!");
if (Replied.exchange(true)) {
elog("Replied twice to message {0}({1})", Method, ID);
@@ -200,34 +202,34 @@ private:
std::lock_guard<std::mutex> Lock(Server->TranspWriter);
Server->Transp.reply(std::move(ID), std::move(Reply));
} else {
- Error Err = Reply.takeError();
+ llvm::Error Err = Reply.takeError();
log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
if (TraceArgs)
- (*TraceArgs)["Error"] = to_string(Err);
+ (*TraceArgs)["Error"] = llvm::to_string(Err);
std::lock_guard<std::mutex> Lock(Server->TranspWriter);
Server->Transp.reply(std::move(ID), std::move(Err));
}
}
};
- StringMap<std::function<void(json::Value)>> Notifications;
- StringMap<std::function<void(json::Value, ReplyOnce)>> Calls;
+ llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
+ llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
// Method calls may be cancelled by ID, so keep track of their state.
// This needs a mutex: handlers may finish on a different thread, and that's
// when we clean up entries in the map.
mutable std::mutex RequestCancelersMutex;
- StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
+ llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
- void onCancel(const json::Value &Params) {
- const json::Value *ID = nullptr;
+ void onCancel(const llvm::json::Value &Params) {
+ const llvm::json::Value *ID = nullptr;
if (auto *O = Params.getAsObject())
ID = O->get("id");
if (!ID) {
elog("Bad cancellation request: {0}", Params);
return;
}
- auto StrID = to_string(*ID);
+ auto StrID = llvm::to_string(*ID);
std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
auto It = RequestCancelers.find(StrID);
if (It != RequestCancelers.end())
@@ -237,9 +239,9 @@ private:
// - allows cancellation using RequestCancelers[ID]
// - cleans up the entry in RequestCancelers when it's no longer needed
// If a client reuses an ID, the last wins and the first cannot be canceled.
- Context cancelableRequestContext(const json::Value &ID) {
+ Context cancelableRequestContext(const llvm::json::Value &ID) {
auto Task = cancelableTask();
- auto StrID = to_string(ID); // JSON-serialize ID for map key.
+ auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
{
std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
@@ -248,7 +250,7 @@ private:
// When the request ends, we can clean up the entry we just added.
// The cookie lets us check that it hasn't been overwritten due to ID
// reuse.
- return Task.first.derive(make_scope_exit([this, StrID, Cookie] {
+ return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
auto It = RequestCancelers.find(StrID);
if (It != RequestCancelers.end() && It->second.second == Cookie)
@@ -260,7 +262,7 @@ private:
};
// call(), notify(), and reply() wrap the Transport, adding logging and locking.
-void ClangdLSPServer::call(StringRef Method, json::Value Params) {
+void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
auto ID = NextCallID++;
log("--> {0}({1})", Method, ID);
// We currently don't handle responses, so no need to store ID anywhere.
@@ -268,21 +270,21 @@ void ClangdLSPServer::call(StringRef Method, json::Value Params) {
Transp.call(Method, std::move(Params), ID);
}
-void ClangdLSPServer::notify(StringRef Method, json::Value Params) {
+void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
log("--> {0}", Method);
std::lock_guard<std::mutex> Lock(TranspWriter);
Transp.notify(Method, std::move(Params));
}
void ClangdLSPServer::onInitialize(const InitializeParams &Params,
- Callback<json::Value> Reply) {
+ Callback<llvm::json::Value> Reply) {
if (Params.rootUri && *Params.rootUri)
ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
else if (Params.rootPath && !Params.rootPath->empty())
ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
if (Server)
- return Reply(make_error<LSPError>("server already initialized",
- ErrorCode::InvalidRequest));
+ return Reply(llvm::make_error<LSPError>("server already initialized",
+ ErrorCode::InvalidRequest));
if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
CompileCommandsDir = Dir;
if (UseDirBasedCDB)
@@ -304,27 +306,27 @@ void ClangdLSPServer::onInitialize(const InitializeParams &Params,
SupportsHierarchicalDocumentSymbol =
Params.capabilities.HierarchicalDocumentSymbol;
SupportFileStatus = Params.initializationOptions.FileStatus;
- Reply(json::Object{
+ Reply(llvm::json::Object{
{{"capabilities",
- json::Object{
+ llvm::json::Object{
{"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
{"documentFormattingProvider", true},
{"documentRangeFormattingProvider", true},
{"documentOnTypeFormattingProvider",
- json::Object{
+ llvm::json::Object{
{"firstTriggerCharacter", "}"},
{"moreTriggerCharacter", {}},
}},
{"codeActionProvider", true},
{"completionProvider",
- json::Object{
+ llvm::json::Object{
{"resolveProvider", false},
// We do extra checks for '>' and ':' in completion to only
// trigger on '->' and '::'.
{"triggerCharacters", {".", ">", ":"}},
}},
{"signatureHelpProvider",
- json::Object{
+ llvm::json::Object{
{"triggerCharacters", {"(", ","}},
}},
{"definitionProvider", true},
@@ -335,7 +337,7 @@ void ClangdLSPServer::onInitialize(const InitializeParams &Params,
{"workspaceSymbolProvider", true},
{"referencesProvider", true},
{"executeCommandProvider",
- json::Object{
+ llvm::json::Object{
{"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
}},
}}}});
@@ -355,8 +357,8 @@ void ClangdLSPServer::onSync(const NoParams &Params,
if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
Reply(nullptr);
else
- Reply(createStringError(llvm::inconvertibleErrorCode(),
- "Not idle after a minute"));
+ Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
+ "Not idle after a minute"));
}
void ClangdLSPServer::onDocumentDidOpen(
@@ -377,7 +379,7 @@ void ClangdLSPServer::onDocumentDidChange(
: WantDiagnostics::No;
PathRef File = Params.textDocument.uri.file();
- Expected<std::string> Contents =
+ llvm::Expected<std::string> Contents =
DraftMgr.updateDraft(File, Params.contentChanges);
if (!Contents) {
// If this fails, we are most likely going to be not in sync anymore with
@@ -397,7 +399,7 @@ void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
}
void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
- Callback<json::Value> Reply) {
+ Callback<llvm::json::Value> Reply) {
auto ApplyEdit = [&](WorkspaceEdit WE) {
ApplyWorkspaceEditParams Edit;
Edit.edit = std::move(WE);
@@ -422,8 +424,8 @@ void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
// We should not get here because ExecuteCommandParams would not have
// parsed in the first place and this handler should not be called. But if
// more commands are added, this will be here has a safe guard.
- Reply(make_error<LSPError>(
- formatv("Unsupported command \"{0}\".", Params.command).str(),
+ Reply(llvm::make_error<LSPError>(
+ llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
ErrorCode::InvalidParams));
}
}
@@ -435,7 +437,7 @@ void ClangdLSPServer::onWorkspaceSymbol(
Params.query, CCOpts.Limit,
Bind(
[this](decltype(Reply) Reply,
- Expected<std::vector<SymbolInformation>> Items) {
+ llvm::Expected<std::vector<SymbolInformation>> Items) {
if (!Items)
return Reply(Items.takeError());
for (auto &Sym : *Items)
@@ -449,17 +451,17 @@ void ClangdLSPServer::onWorkspaceSymbol(
void ClangdLSPServer::onRename(const RenameParams &Params,
Callback<WorkspaceEdit> Reply) {
Path File = Params.textDocument.uri.file();
- Optional<std::string> Code = DraftMgr.getDraft(File);
+ llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
if (!Code)
- return Reply(make_error<LSPError>("onRename called for non-added file",
- ErrorCode::InvalidParams));
+ return Reply(llvm::make_error<LSPError>(
+ "onRename called for non-added file", ErrorCode::InvalidParams));
Server->rename(
File, Params.position, Params.newName,
Bind(
- [File, Code,
- Params](decltype(Reply) Reply,
- Expected<std::vector<tooling::Replacement>> Replacements) {
+ [File, Code, Params](
+ decltype(Reply) Reply,
+ llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
if (!Replacements)
return Reply(Replacements.takeError());
@@ -488,7 +490,7 @@ void ClangdLSPServer::onDocumentOnTypeFormatting(
auto File = Params.textDocument.uri.file();
auto Code = DraftMgr.getDraft(File);
if (!Code)
- return Reply(make_error<LSPError>(
+ return Reply(llvm::make_error<LSPError>(
"onDocumentOnTypeFormatting called for non-added file",
ErrorCode::InvalidParams));
@@ -505,7 +507,7 @@ void ClangdLSPServer::onDocumentRangeFormatting(
auto File = Params.textDocument.uri.file();
auto Code = DraftMgr.getDraft(File);
if (!Code)
- return Reply(make_error<LSPError>(
+ return Reply(llvm::make_error<LSPError>(
"onDocumentRangeFormatting called for non-added file",
ErrorCode::InvalidParams));
@@ -522,9 +524,9 @@ void ClangdLSPServer::onDocumentFormatting(
auto File = Params.textDocument.uri.file();
auto Code = DraftMgr.getDraft(File);
if (!Code)
- return Reply(
- make_error<LSPError>("onDocumentFormatting called for non-added file",
- ErrorCode::InvalidParams));
+ return Reply(llvm::make_error<LSPError>(
+ "onDocumentFormatting called for non-added file",
+ ErrorCode::InvalidParams));
auto ReplacementsOrError = Server->formatFile(*Code, File);
if (ReplacementsOrError)
@@ -540,8 +542,8 @@ flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
const URIForFile &FileURI) {
std::vector<SymbolInformation> Results;
- std::function<void(const DocumentSymbol &, StringRef)> Process =
- [&](const DocumentSymbol &S, Optional<StringRef> ParentName) {
+ std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
+ [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
SymbolInformation SI;
SI.containerName = ParentName ? "" : *ParentName;
SI.name = S.name;
@@ -561,13 +563,13 @@ flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
}
void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
- Callback<json::Value> Reply) {
+ Callback<llvm::json::Value> Reply) {
URIForFile FileURI = Params.textDocument.uri;
Server->documentSymbols(
Params.textDocument.uri.file(),
Bind(
[this, FileURI](decltype(Reply) Reply,
- Expected<std::vector<DocumentSymbol>> Items) {
+ llvm::Expected<std::vector<DocumentSymbol>> Items) {
if (!Items)
return Reply(Items.takeError());
adjustSymbolKinds(*Items, SupportedSymbolKinds);
@@ -579,7 +581,7 @@ void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
std::move(Reply)));
}
-static Optional<Command> asCommand(const CodeAction &Action) {
+static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Command Cmd;
if (Action.command && Action.edit)
return None; // Not representable. (We never emit these anyway).
@@ -598,11 +600,11 @@ static Optional<Command> asCommand(const CodeAction &Action) {
}
void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
- Callback<json::Value> Reply) {
+ Callback<llvm::json::Value> Reply) {
auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
if (!Code)
- return Reply(make_error<LSPError>("onCodeAction called for non-added file",
- ErrorCode::InvalidParams));
+ return Reply(llvm::make_error<LSPError>(
+ "onCodeAction called for non-added file", ErrorCode::InvalidParams));
// We provide a code action for Fixes on the specified diagnostics.
std::vector<CodeAction> Actions;
for (const Diagnostic &D : Params.context.diagnostics) {
@@ -613,13 +615,13 @@ void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
}
if (SupportsCodeAction)
- Reply(json::Array(Actions));
+ Reply(llvm::json::Array(Actions));
else {
std::vector<Command> Commands;
for (const auto &Action : Actions)
if (auto Command = asCommand(Action))
Commands.push_back(std::move(*Command));
- Reply(json::Array(Commands));
+ Reply(llvm::json::Array(Commands));
}
}
@@ -627,23 +629,23 @@ void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Callback<CompletionList> Reply) {
if (!shouldRunCompletion(Params))
return Reply(llvm::make_error<IgnoreCompletionError>());
- Server->codeComplete(
- Params.textDocument.uri.file(), Params.position, CCOpts,
- Bind(
- [this](decltype(Reply) Reply, Expected<CodeCompleteResult> List) {
- if (!List)
- return Reply(List.takeError());
- CompletionList LSPList;
- LSPList.isIncomplete = List->HasMore;
- for (const auto &R : List->Completions) {
- CompletionItem C = R.render(CCOpts);
- C.kind =
- adjustKindToCapability(C.kind, SupportedCompletionItemKinds);
- LSPList.items.push_back(std::move(C));
- }
- return Reply(std::move(LSPList));
- },
- std::move(Reply)));
+ Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
+ Bind(
+ [this](decltype(Reply) Reply,
+ llvm::Expected<CodeCompleteResult> List) {
+ if (!List)
+ return Reply(List.takeError());
+ CompletionList LSPList;
+ LSPList.isIncomplete = List->HasMore;
+ for (const auto &R : List->Completions) {
+ CompletionItem C = R.render(CCOpts);
+ C.kind = adjustKindToCapability(
+ C.kind, SupportedCompletionItemKinds);
+ LSPList.items.push_back(std::move(C));
+ }
+ return Reply(std::move(LSPList));
+ },
+ std::move(Reply)));
}
void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
@@ -660,7 +662,7 @@ void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
Callback<std::string> Reply) {
- Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
+ llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Reply(Result ? URI::createFile(*Result).toString() : "");
}
@@ -672,7 +674,7 @@ void ClangdLSPServer::onDocumentHighlight(
}
void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
- Callback<Optional<Hover>> Reply) {
+ Callback<llvm::Optional<Hover>> Reply) {
Server->findHover(Params.textDocument.uri.file(), Params.position,
std::move(Reply));
}
@@ -719,7 +721,7 @@ void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
const clangd::CodeCompleteOptions &CCOpts,
- Optional<Path> CompileCommandsDir,
+ llvm::Optional<Path> CompileCommandsDir,
bool UseDirBasedCDB,
const ClangdServer::Options &Opts)
: Transp(Transp), MsgHandler(new MessageHandler(*this)), CCOpts(CCOpts),
@@ -771,7 +773,7 @@ bool ClangdLSPServer::run() {
return CleanExit && ShutdownRequestReceived;
}
-std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
+std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
const clangd::Diagnostic &D) {
std::lock_guard<std::mutex> Lock(FixItsMutex);
auto DiagToFixItsIter = FixItsMap.find(File);
@@ -788,7 +790,7 @@ std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
bool ClangdLSPServer::shouldRunCompletion(
const CompletionParams &Params) const {
- StringRef Trigger = Params.context.triggerCharacter;
+ llvm::StringRef Trigger = Params.context.triggerCharacter;
if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
(Trigger != ">" && Trigger != ":"))
return true;
@@ -828,7 +830,7 @@ void ClangdLSPServer::onDiagnosticsReady(PathRef File,
DiagnosticToReplacementMap LocalFixIts; // Temporary storage
for (auto &Diag : Diagnostics) {
toLSPDiags(Diag, URI, DiagOpts,
- [&](clangd::Diagnostic Diag, ArrayRef<Fix> Fixes) {
+ [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
auto &FixItsForDiagnostic = LocalFixIts[Diag];
llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
LSPDiagnostics.push_back(std::move(Diag));
@@ -844,7 +846,7 @@ void ClangdLSPServer::onDiagnosticsReady(PathRef File,
// Publish diagnostics.
notify("textDocument/publishDiagnostics",
- json::Object{
+ llvm::json::Object{
{"uri", URI},
{"diagnostics", std::move(LSPDiagnostics)},
});
diff --git a/clang-tools-extra/clangd/ClangdServer.cpp b/clang-tools-extra/clangd/ClangdServer.cpp
index e554ade874d..f799d6bc670 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -34,7 +34,6 @@
#include <future>
#include <mutex>
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -47,7 +46,7 @@ std::string getStandardResourceDir() {
class RefactoringResultCollector final
: public tooling::RefactoringResultConsumer {
public:
- void handleError(Error Err) override {
+ void handleError(llvm::Error Err) override {
assert(!Result.hasValue());
// FIXME: figure out a way to return better message for DiagnosticError.
// clangd uses llvm::toString to convert the Err to string, however, for
@@ -63,7 +62,7 @@ public:
Result = std::move(SourceReplacements);
}
- Optional<Expected<tooling::AtomicChanges>> Result;
+ llvm::Optional<llvm::Expected<tooling::AtomicChanges>> Result;
};
// Update the FileIndex with new ASTs and plumb the diagnostics responses.
@@ -147,7 +146,7 @@ ClangdServer::ClangdServer(const GlobalCompilationDatabase &CDB,
AddIndex(DynamicIdx.get());
}
-void ClangdServer::addDocument(PathRef File, StringRef Contents,
+void ClangdServer::addDocument(PathRef File, llvm::StringRef Contents,
WantDiagnostics WantDiags) {
// FIXME: some build systems like Bazel will take time to preparing
// environment to build the file, it would be nice if we could emit a
@@ -175,13 +174,13 @@ void ClangdServer::codeComplete(PathRef File, Position Pos,
auto Task = [PCHs, Pos, FS, CodeCompleteOpts,
this](Path File, Callback<CodeCompleteResult> CB,
- Expected<InputsAndPreamble> IP) {
+ llvm::Expected<InputsAndPreamble> IP) {
if (!IP)
return CB(IP.takeError());
if (isCancelled())
- return CB(make_error<CancelledError>());
+ return CB(llvm::make_error<CancelledError>());
- Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
+ llvm::Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
if (CodeCompleteOpts.Index && CodeCompleteOpts.SpeculativeIndexRequest) {
SpecFuzzyFind.emplace();
{
@@ -222,7 +221,7 @@ void ClangdServer::signatureHelp(PathRef File, Position Pos,
auto FS = FSProvider.getFileSystem();
auto *Index = this->Index;
auto Action = [Pos, FS, PCHs, Index](Path File, Callback<SignatureHelp> CB,
- Expected<InputsAndPreamble> IP) {
+ llvm::Expected<InputsAndPreamble> IP) {
if (!IP)
return CB(IP.takeError());
@@ -239,43 +238,44 @@ void ClangdServer::signatureHelp(PathRef File, Position Pos,
Bind(Action, File.str(), std::move(CB)));
}
-Expected<tooling::Replacements>
-ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
- Expected<size_t> Begin = positionToOffset(Code, Rng.start);
+llvm::Expected<tooling::Replacements>
+ClangdServer::formatRange(llvm::StringRef Code, PathRef File, Range Rng) {
+ llvm::Expected<size_t> Begin = positionToOffset(Code, Rng.start);
if (!Begin)
return Begin.takeError();
- Expected<size_t> End = positionToOffset(Code, Rng.end);
+ llvm::Expected<size_t> End = positionToOffset(Code, Rng.end);
if (!End)
return End.takeError();
return formatCode(Code, File, {tooling::Range(*Begin, *End - *Begin)});
}
-Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
- PathRef File) {
+llvm::Expected<tooling::Replacements>
+ClangdServer::formatFile(llvm::StringRef Code, PathRef File) {
// Format everything.
return formatCode(Code, File, {tooling::Range(0, Code.size())});
}
-Expected<tooling::Replacements>
-ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
+llvm::Expected<tooling::Replacements>
+ClangdServer::formatOnType(llvm::StringRef Code, PathRef File, Position Pos) {
// Look for the previous opening brace from the character position and
// format starting from there.
- Expected<size_t> CursorPos = positionToOffset(Code, Pos);
+ llvm::Expected<size_t> CursorPos = positionToOffset(Code, Pos);
if (!CursorPos)
return CursorPos.takeError();
- size_t PreviousLBracePos = StringRef(Code).find_last_of('{', *CursorPos);
- if (PreviousLBracePos == StringRef::npos)
+ size_t PreviousLBracePos =
+ llvm::StringRef(Code).find_last_of('{', *CursorPos);
+ if (PreviousLBracePos == llvm::StringRef::npos)
PreviousLBracePos = *CursorPos;
size_t Len = *CursorPos - PreviousLBracePos;
return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
}
-void ClangdServer::rename(PathRef File, Position Pos, StringRef NewName,
+void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
Callback<std::vector<tooling::Replacement>> CB) {
auto Action = [Pos](Path File, std::string NewName,
Callback<std::vector<tooling::Replacement>> CB,
- Expected<InputsAndAST> InpAST) {
+ llvm::Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
auto &AST = InpAST->AST;
@@ -323,15 +323,16 @@ void ClangdServer::rename(PathRef File, Position Pos, StringRef NewName,
}
void ClangdServer::dumpAST(PathRef File,
- unique_function<void(std::string)> Callback) {
- auto Action = [](decltype(Callback) Callback, Expected<InputsAndAST> InpAST) {
+ llvm::unique_function<void(std::string)> Callback) {
+ auto Action = [](decltype(Callback) Callback,
+ llvm::Expected<InputsAndAST> InpAST) {
if (!InpAST) {
llvm::consumeError(InpAST.takeError());
return Callback("<no-ast>");
}
std::string Result;
- raw_string_ostream ResultOS(Result);
+ llvm::raw_string_ostream ResultOS(Result);
clangd::dumpAST(InpAST->AST, ResultOS);
ResultOS.flush();
@@ -344,7 +345,7 @@ void ClangdServer::dumpAST(PathRef File,
void ClangdServer::findDefinitions(PathRef File, Position Pos,
Callback<std::vector<Location>> CB) {
auto Action = [Pos, this](Callback<std::vector<Location>> CB,
- Expected<InputsAndAST> InpAST) {
+ llvm::Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
CB(clangd::findDefinitions(InpAST->AST, Pos, Index));
@@ -353,13 +354,13 @@ void ClangdServer::findDefinitions(PathRef File, Position Pos,
WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
}
-Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
+llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
- StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
- ".c++", ".m", ".mm"};
- StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
+ llvm::StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
+ ".c++", ".m", ".mm"};
+ llvm::StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
- StringRef PathExt = sys::path::extension(Path);
+ llvm::StringRef PathExt = llvm::sys::path::extension(Path);
// Lookup in a list of known extensions.
auto SourceIter =
@@ -381,28 +382,28 @@ Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
// Array to lookup extensions for the switch. An opposite of where original
// extension was found.
- ArrayRef<StringRef> NewExts;
+ llvm::ArrayRef<llvm::StringRef> NewExts;
if (IsSource)
NewExts = HeaderExtensions;
else
NewExts = SourceExtensions;
// Storage for the new path.
- SmallString<128> NewPath = StringRef(Path);
+ llvm::SmallString<128> NewPath = llvm::StringRef(Path);
// Instance of vfs::FileSystem, used for file existence checks.
auto FS = FSProvider.getFileSystem();
// Loop through switched extension candidates.
- for (StringRef NewExt : NewExts) {
- sys::path::replace_extension(NewPath, NewExt);
+ for (llvm::StringRef NewExt : NewExts) {
+ llvm::sys::path::replace_extension(NewPath, NewExt);
if (FS->exists(NewPath))
return NewPath.str().str(); // First str() to convert from SmallString to
// StringRef, second to convert from StringRef
// to std::string
// Also check NewExt in upper-case, just in case.
- sys::path::replace_extension(NewPath, NewExt.upper());
+ llvm::sys::path::replace_extension(NewPath, NewExt.upper());
if (FS->exists(NewPath))
return NewPath.str().str();
}
@@ -410,9 +411,9 @@ Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
return None;
}
-Expected<tooling::Replacements>
-ClangdServer::formatCode(StringRef Code, PathRef File,
- ArrayRef<tooling::Range> Ranges) {
+llvm::Expected<tooling::Replacements>
+ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
+ llvm::ArrayRef<tooling::Range> Ranges) {
// Call clang-format.
auto FS = FSProvider.getFileSystem();
auto Style = format::getStyle(format::DefaultFormatStyle, File,
@@ -435,7 +436,7 @@ ClangdServer::formatCode(StringRef Code, PathRef File,
void ClangdServer::findDocumentHighlights(
PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
auto Action = [Pos](Callback<std::vector<DocumentHighlight>> CB,
- Expected<InputsAndAST> InpAST) {
+ llvm::Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
@@ -445,9 +446,9 @@ void ClangdServer::findDocumentHighlights(
}
void ClangdServer::findHover(PathRef File, Position Pos,
- Callback<Optional<Hover>> CB) {
- auto Action = [Pos](Callback<Optional<Hover>> CB,
- Expected<InputsAndAST> InpAST) {
+ Callback<llvm::Optional<Hover>> CB) {
+ auto Action = [Pos](Callback<llvm::Optional<Hover>> CB,
+ llvm::Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
CB(clangd::getHover(InpAST->AST, Pos));
@@ -458,7 +459,7 @@ void ClangdServer::findHover(PathRef File, Position Pos,
tooling::CompileCommand ClangdServer::getCompileCommand(PathRef File) {
trace::Span Span("GetCompileCommand");
- Optional<tooling::CompileCommand> C = CDB.getCompileCommand(File);
+ llvm::Optional<tooling::CompileCommand> C = CDB.getCompileCommand(File);
if (!C) // FIXME: Suppress diagnostics? Let the user know?
C = CDB.getFallbackCommand(File);
@@ -474,7 +475,8 @@ void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
}
void ClangdServer::workspaceSymbols(
- StringRef Query, int Limit, Callback<std::vector<SymbolInformation>> CB) {
+ llvm::StringRef Query, int Limit,
+ Callback<std::vector<SymbolInformation>> CB) {
std::string QueryCopy = Query;
WorkScheduler.run(
"getWorkspaceSymbols",
@@ -486,7 +488,7 @@ void ClangdServer::workspaceSymbols(
std::move(CB)));
}
-void ClangdServer::documentSymbols(StringRef File,
+void ClangdServer::documentSymbols(llvm::StringRef File,
Callback<std::vector<DocumentSymbol>> CB) {
auto Action = [](Callback<std::vector<DocumentSymbol>> CB,
llvm::Expected<InputsAndAST> InpAST) {
@@ -501,7 +503,7 @@ void ClangdServer::documentSymbols(StringRef File,
void ClangdServer::findReferences(PathRef File, Position Pos,
Callback<std::vector<Location>> CB) {
auto Action = [Pos, this](Callback<std::vector<Location>> CB,
- Expected<InputsAndAST> InpAST) {
+ llvm::Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
CB(clangd::findReferences(InpAST->AST, Pos, Index));
@@ -513,7 +515,7 @@ void ClangdServer::findReferences(PathRef File, Position Pos,
void ClangdServer::symbolInfo(PathRef File, Position Pos,
Callback<std::vector<SymbolDetails>> CB) {
auto Action = [Pos](Callback<std::vector<SymbolDetails>> CB,
- Expected<InputsAndAST> InpAST) {
+ llvm::Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
CB(clangd::getSymbolInfo(InpAST->AST, Pos));
@@ -528,7 +530,7 @@ ClangdServer::getUsedBytesPerFile() const {
}
LLVM_NODISCARD bool
-ClangdServer::blockUntilIdleForTest(Optional<double> TimeoutSeconds) {
+ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds)) &&
(!BackgroundIdx ||
BackgroundIdx->blockUntilIdleForTest(TimeoutSeconds));
diff --git a/clang-tools-extra/clangd/ClangdUnit.cpp b/clang-tools-extra/clangd/ClangdUnit.cpp
index 013d180b7a5..5add1179fb4 100644
--- a/clang-tools-extra/clangd/ClangdUnit.cpp
+++ b/clang-tools-extra/clangd/ClangdUnit.cpp
@@ -36,7 +36,6 @@
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -45,7 +44,7 @@ bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
const tooling::CompileCommand &RHS) {
// We don't check for Output, it should not matter to clangd.
return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
- makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
+ llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
}
template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
@@ -80,8 +79,8 @@ public:
std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
protected:
- std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
- StringRef InFile) override {
+ std::unique_ptr<ASTConsumer>
+ CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
}
@@ -179,12 +178,12 @@ private:
if (Inc.Resolved != "")
File = SM.getFileManager().getFile(Inc.Resolved);
- StringRef WrittenFilename =
- StringRef(Inc.Written).drop_front().drop_back();
- bool Angled = StringRef(Inc.Written).startswith("<");
+ llvm::StringRef WrittenFilename =
+ llvm::StringRef(Inc.Written).drop_front().drop_back();
+ bool Angled = llvm::StringRef(Inc.Written).startswith("<");
// Re-lex the #include directive to find its interesting parts.
- StringRef Src = SM.getBufferData(SM.getMainFileID());
+ llvm::StringRef Src = SM.getBufferData(SM.getMainFileID());
Lexer RawLexer(SM.getLocForStartOfFile(SM.getMainFileID()), LangOpts,
Src.begin(), Src.begin() + Inc.HashOffset, Src.end());
Token HashTok, IncludeTok, FilenameTok;
@@ -205,7 +204,7 @@ private:
if (File)
Delegate->FileSkipped(*File, FilenameTok, Inc.FileKind);
else {
- SmallString<1> UnusedRecovery;
+ llvm::SmallString<1> UnusedRecovery;
Delegate->FileNotFound(WrittenFilename, UnusedRecovery);
}
}
@@ -220,16 +219,16 @@ private:
} // namespace
-void dumpAST(ParsedAST &AST, raw_ostream &OS) {
+void dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
}
-Optional<ParsedAST>
+llvm::Optional<ParsedAST>
ParsedAST::build(std::unique_ptr<CompilerInvocation> CI,
std::shared_ptr<const PreambleData> Preamble,
- std::unique_ptr<MemoryBuffer> Buffer,
+ std::unique_ptr<llvm::MemoryBuffer> Buffer,
std::shared_ptr<PCHContainerOperations> PCHs,
- IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
+ llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
assert(CI);
// Command-line parsing sets DisableFree to true by default, but we don't want
// to leak memory in clangd.
@@ -362,7 +361,7 @@ const Preprocessor &ParsedAST::getPreprocessor() const {
return Clang->getPreprocessor();
}
-ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
+llvm::ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
return LocalTopLevelDecls;
}
@@ -438,7 +437,7 @@ buildCompilerInvocation(const ParseInputs &Inputs) {
// FIXME(ibiryukov): store diagnostics from CommandLine when we start
// reporting them.
IgnoreDiagnostics IgnoreDiagnostics;
- IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
+ llvm::IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
CompilerInstance::createDiagnostics(new DiagnosticOptions,
&IgnoreDiagnostics, false);
std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
@@ -460,7 +459,7 @@ buildPreamble(PathRef FileName, CompilerInvocation &CI,
PreambleParsedCallback PreambleCallback) {
// Note that we don't need to copy the input contents, preamble can live
// without those.
- auto ContentsBuffer = MemoryBuffer::getMemBuffer(Inputs.Contents);
+ auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Inputs.Contents);
auto Bounds =
ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
@@ -468,7 +467,7 @@ buildPreamble(PathRef FileName, CompilerInvocation &CI,
compileCommandsAreEqual(Inputs.CompileCommand, OldCompileCommand) &&
OldPreamble->Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
Inputs.FS.get())) {
- vlog("Reusing preamble for file {0}", Twine(FileName));
+ vlog("Reusing preamble for file {0}", llvm::Twine(FileName));
return OldPreamble;
}
vlog("Preamble for file {0} cannot be reused. Attempting to rebuild it.",
@@ -477,7 +476,7 @@ buildPreamble(PathRef FileName, CompilerInvocation &CI,
trace::Span Tracer("BuildPreamble");
SPAN_ATTACH(Tracer, "File", FileName);
StoreDiags PreambleDiagnostics;
- IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
+ llvm::IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
&PreambleDiagnostics, false);
@@ -496,7 +495,7 @@ buildPreamble(PathRef FileName, CompilerInvocation &CI,
// dirs.
}
- SmallString<32> AbsFileName(FileName);
+ llvm::SmallString<32> AbsFileName(FileName);
Inputs.FS->makeAbsolute(AbsFileName);
auto StatCache = llvm::make_unique<PreambleFileStatusCache>(AbsFileName);
auto BuiltPreamble = PrecompiledPreamble::Build(
@@ -520,11 +519,11 @@ buildPreamble(PathRef FileName, CompilerInvocation &CI,
}
}
-Optional<ParsedAST> buildAST(PathRef FileName,
- std::unique_ptr<CompilerInvocation> Invocation,
- const ParseInputs &Inputs,
- std::shared_ptr<const PreambleData> Preamble,
- std::shared_ptr<PCHContainerOperations> PCHs) {
+llvm::Optional<ParsedAST>
+buildAST(PathRef FileName, std::unique_ptr<CompilerInvocation> Invocation,
+ const ParseInputs &Inputs,
+ std::shared_ptr<const PreambleData> Preamble,
+ std::shared_ptr<PCHContainerOperations> PCHs) {
trace::Span Tracer("BuildAST");
SPAN_ATTACH(Tracer, "File", FileName);
@@ -537,9 +536,10 @@ Optional<ParsedAST> buildAST(PathRef FileName,
// dirs.
}
- return ParsedAST::build(
- llvm::make_unique<CompilerInvocation>(*Invocation), Preamble,
- MemoryBuffer::getMemBufferCopy(Inputs.Contents), PCHs, std::move(VFS));
+ return ParsedAST::build(llvm::make_unique<CompilerInvocation>(*Invocation),
+ Preamble,
+ llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents),
+ PCHs, std::move(VFS));
}
SourceLocation getBeginningOfIdentifier(ParsedAST &Unit, const Position &Pos,
diff --git a/clang-tools-extra/clangd/CodeComplete.cpp b/clang-tools-extra/clangd/CodeComplete.cpp
index be614536b11..7642ea9da7d 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -59,7 +59,6 @@
// We log detailed candidate here if you run with -debug-only=codecomplete.
#define DEBUG_TYPE "CodeComplete"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -181,7 +180,8 @@ std::string getOptionalParameters(const CodeCompletionString &CCS,
/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
/// include.
-static Expected<HeaderFile> toHeaderFile(StringRef Header, StringRef HintPath) {
+static llvm::Expected<HeaderFile> toHeaderFile(llvm::StringRef Header,
+ llvm::StringRef HintPath) {
if (isLiteralInclude(Header))
return HeaderFile{Header.str(), /*Verbatim=*/true};
auto U = URI::parse(Header);
@@ -203,16 +203,16 @@ static Expected<HeaderFile> toHeaderFile(StringRef Header, StringRef HintPath) {
/// A code completion result, in clang-native form.
/// It may be promoted to a CompletionItem if it's among the top-ranked results.
struct CompletionCandidate {
- StringRef Name; // Used for filtering and sorting.
+ llvm::StringRef Name; // Used for filtering and sorting.
// We may have a result from Sema, from the index, or both.
const CodeCompletionResult *SemaResult = nullptr;
const Symbol *IndexResult = nullptr;
- SmallVector<StringRef, 1> RankedIncludeHeaders;
+ llvm::SmallVector<llvm::StringRef, 1> RankedIncludeHeaders;
// Returns a token identifying the overload set this is part of.
// 0 indicates it's not part of any overload set.
size_t overloadSet() const {
- SmallString<256> Scratch;
+ llvm::SmallString<256> Scratch;
if (IndexResult) {
switch (IndexResult->SymInfo.Kind) {
case index::SymbolKind::ClassMethod:
@@ -226,7 +226,7 @@ struct CompletionCandidate {
case index::SymbolKind::Function:
// We can't group overloads together that need different #includes.
// This could break #include insertion.
- return hash_combine(
+ return llvm::hash_combine(
(IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
headerToInsertIfAllowed().getValueOr(""));
default:
@@ -239,14 +239,15 @@ struct CompletionCandidate {
if (!D || !D->isFunctionOrFunctionTemplate())
return 0;
{
- raw_svector_ostream OS(Scratch);
+ llvm::raw_svector_ostream OS(Scratch);
D->printQualifiedName(OS);
}
- return hash_combine(Scratch, headerToInsertIfAllowed().getValueOr(""));
+ return llvm::hash_combine(Scratch,
+ headerToInsertIfAllowed().getValueOr(""));
}
// The best header to include if include insertion is allowed.
- Optional<StringRef> headerToInsertIfAllowed() const {
+ llvm::Optional<llvm::StringRef> headerToInsertIfAllowed() const {
if (RankedIncludeHeaders.empty())
return None;
if (SemaResult && SemaResult->Declaration) {
@@ -260,7 +261,7 @@ struct CompletionCandidate {
return RankedIncludeHeaders[0];
}
- using Bundle = SmallVector<CompletionCandidate, 4>;
+ using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
};
using ScoredBundle =
std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
@@ -283,8 +284,9 @@ struct ScoredBundleGreater {
struct CodeCompletionBuilder {
CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
CodeCompletionString *SemaCCS,
- ArrayRef<std::string> QueryScopes,
- const IncludeInserter &Includes, StringRef FileName,
+ llvm::ArrayRef<std::string> QueryScopes,
+ const IncludeInserter &Includes,
+ llvm::StringRef FileName,
CodeCompletionContext::Kind ContextKind,
const CodeCompleteOptions &Opts)
: ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments),
@@ -292,7 +294,7 @@ struct CodeCompletionBuilder {
add(C, SemaCCS);
if (C.SemaResult) {
Completion.Origin |= SymbolOrigin::AST;
- Completion.Name = StringRef(SemaCCS->getTypedText());
+ Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
if (Completion.Scope.empty()) {
if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
(C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
@@ -330,9 +332,9 @@ struct CodeCompletionBuilder {
// If the completion was visible to Sema, no qualifier is needed. This
// avoids unneeded qualifiers in cases like with `using ns::X`.
if (Completion.RequiredQualifier.empty() && !C.SemaResult) {
- StringRef ShortestQualifier = C.IndexResult->Scope;
- for (StringRef Scope : QueryScopes) {
- StringRef Qualifier = C.IndexResult->Scope;
+ llvm::StringRef ShortestQualifier = C.IndexResult->Scope;
+ for (llvm::StringRef Scope : QueryScopes) {
+ llvm::StringRef Qualifier = C.IndexResult->Scope;
if (Qualifier.consume_front(Scope) &&
Qualifier.size() < ShortestQualifier.size())
ShortestQualifier = Qualifier;
@@ -343,8 +345,8 @@ struct CodeCompletionBuilder {
}
// Turn absolute path into a literal string that can be #included.
- auto Inserted =
- [&](StringRef Header) -> Expected<std::pair<std::string, bool>> {
+ auto Inserted = [&](llvm::StringRef Header)
+ -> llvm::Expected<std::pair<std::string, bool>> {
auto ResolvedDeclaring =
toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
if (!ResolvedDeclaring)
@@ -462,7 +464,7 @@ private:
// foo<${1:class}>(${2:int p1}).
// We transform this pattern to '<$1>()$0' or '<$0>()'.
- bool EmptyArgs = StringRef(*Snippet).endswith("()");
+ bool EmptyArgs = llvm::StringRef(*Snippet).endswith("()");
if (Snippet->front() == '<')
return EmptyArgs ? "<$1>()$0" : "<$1>($0)";
if (Snippet->front() == '(')
@@ -476,7 +478,7 @@ private:
// Classes and template using aliases can only have template arguments,
// e.g. Foo<${1:class}>.
- if (StringRef(*Snippet).endswith("<>"))
+ if (llvm::StringRef(*Snippet).endswith("<>"))
return "<>"; // can happen with defaulted template arguments.
return "<$0>";
}
@@ -492,14 +494,14 @@ private:
ASTContext &ASTCtx;
CodeCompletion Completion;
- SmallVector<BundledEntry, 1> Bundled;
+ llvm::SmallVector<BundledEntry, 1> Bundled;
bool ExtractDocumentation;
bool EnableFunctionArgSnippets;
};
// Determine the symbol ID for a Sema code completion result, if possible.
-Optional<SymbolID> getSymbolID(const CodeCompletionResult &R,
- const SourceManager &SM) {
+llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R,
+ const SourceManager &SM) {
switch (R.Kind) {
case CodeCompletionResult::RK_Declaration:
case CodeCompletionResult::RK_Pattern: {
@@ -539,13 +541,13 @@ struct SpecifiedScope {
std::vector<std::string> AccessibleScopes;
// The full scope qualifier as typed by the user (without the leading "::").
// Set if the qualifier is not fully resolved by Sema.
- Optional<std::string> UnresolvedQualifier;
+ llvm::Optional<std::string> UnresolvedQualifier;
// Construct scopes being queried in indexes. The results are deduplicated.
// This method format the scopes to match the index request representation.
std::vector<std::string> scopesForIndexQuery() {
std::set<std::string> Results;
- for (StringRef AS : AccessibleScopes)
+ for (llvm::StringRef AS : AccessibleScopes)
Results.insert(
((UnresolvedQualifier ? *UnresolvedQualifier : "") + AS).str());
return {Results.begin(), Results.end()};
@@ -688,7 +690,7 @@ static bool isBlacklistedMember(const NamedDecl &D) {
// within the callback.
struct CompletionRecorder : public CodeCompleteConsumer {
CompletionRecorder(const CodeCompleteOptions &Opts,
- unique_function<void()> ResultsCallback)
+ llvm::unique_function<void()> ResultsCallback)
: CodeCompleteConsumer(Opts.getClangCompleteOpts(),
/*OutputIsBinary=*/false),
CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
@@ -766,7 +768,7 @@ struct CompletionRecorder : public CodeCompleteConsumer {
// Returns the filtering/sorting name for Result, which must be from Results.
// Returned string is owned by this recorder (or the AST).
- StringRef getName(const CodeCompletionResult &Result) {
+ llvm::StringRef getName(const CodeCompletionResult &Result) {
switch (Result.Kind) {
case CodeCompletionResult::RK_Declaration:
if (auto *ID = Result.Declaration->getIdentifier())
@@ -796,13 +798,13 @@ private:
CodeCompleteOptions Opts;
std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
CodeCompletionTUInfo CCTUInfo;
- unique_function<void()> ResultsCallback;
+ llvm::unique_function<void()> ResultsCallback;
};
struct ScoredSignature {
// When set, requires documentation to be requested from the index with this
// ID.
- Optional<SymbolID> IDForDoc;
+ llvm::Optional<SymbolID> IDForDoc;
SignatureInformation Signature;
SignatureQualitySignals Quality;
};
@@ -862,7 +864,7 @@ public:
// Sema does not load the docs from the preamble, so we need to fetch extra
// docs from the index instead.
- DenseMap<SymbolID, std::string> FetchedDocs;
+ llvm::DenseMap<SymbolID, std::string> FetchedDocs;
if (Index) {
LookupRequest IndexRequest;
for (const auto &S : ScoredSignatures) {
@@ -930,7 +932,7 @@ private:
// CompletionString.h.
ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
const CodeCompletionString &CCS,
- StringRef DocComment) const {
+ llvm::StringRef DocComment) const {
SignatureInformation Signature;
SignatureQualitySignals Signal;
const char *ReturnType = nullptr;
@@ -1002,9 +1004,9 @@ struct SemaCompleteInput {
PathRef FileName;
const tooling::CompileCommand &Command;
const PreambleData *Preamble;
- StringRef Contents;
+ llvm::StringRef Contents;
Position Pos;
- IntrusiveRefCntPtr<vfs::FileSystem> VFS;
+ llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
std::shared_ptr<PCHContainerOperations> PCHs;
};
@@ -1025,7 +1027,7 @@ bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
// working dirs.
}
- IntrusiveRefCntPtr<vfs::FileSystem> VFS = Input.VFS;
+ llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = Input.VFS;
if (Input.Preamble && Input.Preamble->StatCache)
VFS = Input.Preamble->StatCache->getConsumingFS(std::move(VFS));
IgnoreDiagnostics DummyDiagsConsumer;
@@ -1056,8 +1058,8 @@ bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
FrontendOpts.CodeCompletionAt.Column) =
offsetToClangLineColumn(Input.Contents, *Offset);
- std::unique_ptr<MemoryBuffer> ContentsBuffer =
- MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
+ std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
+ llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
// The diagnostic options must be set before creating a CompilerInstance.
CI->getDiagnosticOpts().IgnoreWarnings = true;
// We reuse the preamble whether it's valid or not. This is a
@@ -1139,8 +1141,10 @@ std::future<SymbolSlab> startAsyncFuzzyFind(const SymbolIndex &Index,
// Creates a `FuzzyFindRequest` based on the cached index request from the
// last completion, if any, and the speculated completion filter text in the
// source code.
-Optional<FuzzyFindRequest> speculativeFuzzyFindRequestForCompletion(
- FuzzyFindRequest CachedReq, PathRef File, StringRef Content, Position Pos) {
+llvm::Optional<FuzzyFindRequest>
+speculativeFuzzyFindRequestForCompletion(FuzzyFindRequest CachedReq,
+ PathRef File, llvm::StringRef Content,
+ Position Pos) {
auto Filter = speculateCompletionFilter(Content, Pos);
if (!Filter) {
elog("Failed to speculate filter text for code completion at Pos "
@@ -1155,7 +1159,7 @@ Optional<FuzzyFindRequest> speculativeFuzzyFindRequestForCompletion(
// Returns the most popular include header for \p Sym. If two headers are
// equally popular, prefer the shorter one. Returns empty string if \p Sym has
// no include header.
-SmallVector<StringRef, 1> getRankedIncludes(const Symbol &Sym) {
+llvm::SmallVector<llvm::StringRef, 1> getRankedIncludes(const Symbol &Sym) {
auto Includes = Sym.IncludeHeaders;
// Sort in descending order by reference count and header length.
llvm::sort(Includes, [](const Symbol::IncludeHeaderWithReferences &LHS,
@@ -1164,7 +1168,7 @@ SmallVector<StringRef, 1> getRankedIncludes(const Symbol &Sym) {
return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
return LHS.References > RHS.References;
});
- SmallVector<StringRef, 1> Headers;
+ llvm::SmallVector<llvm::StringRef, 1> Headers;
for (const auto &Include : Includes)
Headers.push_back(Include.IncludeHeader);
return Headers;
@@ -1209,22 +1213,22 @@ class CodeCompleteFlow {
CompletionRecorder *Recorder = nullptr;
int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
bool Incomplete = false; // Would more be available with a higher limit?
- Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
+ llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
std::vector<std::string> QueryScopes; // Initialized once Sema runs.
// Initialized once QueryScopes is initialized, if there are scopes.
- Optional<ScopeDistance> ScopeProximity;
+ llvm::Optional<ScopeDistance> ScopeProximity;
llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs.
// Whether to query symbols from any scope. Initialized once Sema runs.
bool AllScopes = false;
// Include-insertion and proximity scoring rely on the include structure.
// This is available after Sema has run.
- Optional<IncludeInserter> Inserter; // Available during runWithSema.
- Optional<URIDistance> FileProximity; // Initialized once Sema runs.
+ llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
+ llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
/// Speculative request based on the cached request and the filter text before
/// the cursor.
/// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
/// set and contains a cached request.
- Optional<FuzzyFindRequest> SpecReq;
+ llvm::Optional<FuzzyFindRequest> SpecReq;
public:
// A CodeCompleteFlow object is only useful for calling run() exactly once.
@@ -1274,7 +1278,7 @@ public:
// The per-result proximity scoring is (amortized) very cheap.
FileDistanceOptions ProxOpts{}; // Use defaults.
const auto &SM = Recorder->CCSema->getSourceManager();
- StringMap<SourceParams> ProxSources;
+ llvm::StringMap<SourceParams> ProxSources;
for (auto &Entry : Includes.includeDepth(
SM.getFileEntryForID(SM.getMainFileID())->getName())) {
auto &Source = ProxSources[Entry.getKey()];
@@ -1294,7 +1298,7 @@ public:
log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
"expected type {3}",
getCompletionKindString(Recorder->CCContext.getKind()),
- join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+ llvm::join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
: "<none>");
});
@@ -1419,7 +1423,7 @@ private:
const SymbolSlab &IndexResults) {
trace::Span Tracer("Merge and score results");
std::vector<CompletionCandidate::Bundle> Bundles;
- DenseMap<size_t, size_t> BundleLookup;
+ llvm::DenseMap<size_t, size_t> BundleLookup;
auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
const Symbol *IndexResult) {
CompletionCandidate C;
@@ -1438,7 +1442,7 @@ private:
Bundles.back().push_back(std::move(C));
}
};
- DenseSet<const Symbol *> UsedIndexResults;
+ llvm::DenseSet<const Symbol *> UsedIndexResults;
auto CorrespondingIndexResult =
[&](const CodeCompletionResult &SemaResult) -> const Symbol * {
if (auto SymID =
@@ -1468,7 +1472,7 @@ private:
return std::move(Top).items();
}
- Optional<float> fuzzyScore(const CompletionCandidate &C) {
+ llvm::Optional<float> fuzzyScore(const CompletionCandidate &C) {
// Macros can be very spammy, so we only support prefix completion.
// We won't end up with underfull index results, as macros are sema-only.
if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
@@ -1535,8 +1539,8 @@ private:
: Scores.Quality;
dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
- to_string(Origin), Scores.Total, to_string(Quality),
- to_string(Relevance));
+ llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
+ llvm::to_string(Relevance));
NSema += bool(Origin & SymbolOrigin::AST);
NIndex += FromIndex;
@@ -1546,7 +1550,7 @@ private:
}
CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
- Optional<CodeCompletionBuilder> Builder;
+ llvm::Optional<CodeCompletionBuilder> Builder;
for (const auto &Item : Bundle) {
CodeCompletionString *SemaCCS =
Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
@@ -1584,12 +1588,13 @@ clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
return Result;
}
-Expected<StringRef> speculateCompletionFilter(StringRef Content, Position Pos) {
+llvm::Expected<llvm::StringRef>
+speculateCompletionFilter(llvm::StringRef Content, Position Pos) {
auto Offset = positionToOffset(Content, Pos);
if (!Offset)
- return make_error<StringError>(
+ return llvm::make_error<llvm::StringError>(
"Failed to convert position to offset in content.",
- inconvertibleErrorCode());
+ llvm::inconvertibleErrorCode());
if (*Offset == 0)
return "";
@@ -1610,8 +1615,8 @@ Expected<StringRef> speculateCompletionFilter(StringRef Content, Position Pos) {
CodeCompleteResult
codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
- const PreambleData *Preamble, StringRef Contents, Position Pos,
- IntrusiveRefCntPtr<vfs::FileSystem> VFS,
+ const PreambleData *Preamble, llvm::StringRef Contents,
+ Position Pos, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
std::shared_ptr<PCHContainerOperations> PCHs,
CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind) {
return CodeCompleteFlow(FileName,
@@ -1622,9 +1627,9 @@ codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
SignatureHelp signatureHelp(PathRef FileName,
const tooling::CompileCommand &Command,
- const PreambleData *Preamble, StringRef Contents,
- Position Pos,
- IntrusiveRefCntPtr<vfs::FileSystem> VFS,
+ const PreambleData *Preamble,
+ llvm::StringRef Contents, Position Pos,
+ llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
std::shared_ptr<PCHContainerOperations> PCHs,
const SymbolIndex *Index) {
SignatureHelp Result;
@@ -1669,12 +1674,12 @@ CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
LSP.label = ((InsertInclude && InsertInclude->Insertion)
? Opts.IncludeIndicator.Insert
: Opts.IncludeIndicator.NoInsert) +
- (Opts.ShowOrigins ? "[" + to_string(Origin) + "]" : "") +
+ (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
RequiredQualifier + Name + Signature;
LSP.kind = Kind;
- LSP.detail =
- BundleSize > 1 ? formatv("[{0} overloads]", BundleSize) : ReturnType;
+ LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
+ : ReturnType;
LSP.deprecated = Deprecated;
if (InsertInclude)
LSP.detail += "\n" + InsertInclude->Header;
@@ -1711,12 +1716,13 @@ CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
return LSP;
}
-raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CodeCompletion &C) {
// For now just lean on CompletionItem.
return OS << C.render(CodeCompleteOptions());
}
-raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+ const CodeCompleteResult &R) {
OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
<< " (" << getCompletionKindString(R.Context) << ")"
<< " items:\n";
diff --git a/clang-tools-extra/clangd/CodeCompletionStrings.cpp b/clang-tools-extra/clangd/CodeCompletionStrings.cpp
index eeec99cafe9..42a8693f482 100644
--- a/clang-tools-extra/clangd/CodeCompletionStrings.cpp
+++ b/clang-tools-extra/clangd/CodeCompletionStrings.cpp
@@ -14,17 +14,16 @@
#include "clang/Basic/SourceManager.h"
#include <utility>
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
return Chunk.Kind == CodeCompletionString::CK_Informative &&
- StringRef(Chunk.Text).endswith("::");
+ llvm::StringRef(Chunk.Text).endswith("::");
}
-void appendEscapeSnippet(const StringRef Text, std::string *Out) {
+void appendEscapeSnippet(const llvm::StringRef Text, std::string *Out) {
for (const auto Character : Text) {
if (Character == '$' || Character == '}' || Character == '\\')
Out->push_back('\\');
@@ -32,13 +31,13 @@ void appendEscapeSnippet(const StringRef Text, std::string *Out) {
}
}
-bool looksLikeDocComment(StringRef CommentText) {
+bool looksLikeDocComment(llvm::StringRef CommentText) {
// We don't report comments that only contain "special" chars.
// This avoids reporting various delimiters, like:
// =================
// -----------------
// *****************
- return CommentText.find_first_not_of("/*-= \t\r\n") != StringRef::npos;
+ return CommentText.find_first_not_of("/*-= \t\r\n") != llvm::StringRef::npos;
}
} // namespace
@@ -97,7 +96,7 @@ void getSignature(const CodeCompletionString &CCS, std::string *Signature,
// treat them carefully. For Objective-C methods, all typed-text chunks
// will end in ':' (unless there are no arguments, in which case we
// can safely treat them as C++).
- if (!StringRef(Chunk.Text).endswith(":")) { // Treat as C++.
+ if (!llvm::StringRef(Chunk.Text).endswith(":")) { // Treat as C++.
if (RequiredQualifiers)
*RequiredQualifiers = std::move(*Signature);
Signature->clear();
@@ -171,7 +170,7 @@ void getSignature(const CodeCompletionString &CCS, std::string *Signature,
}
std::string formatDocumentation(const CodeCompletionString &CCS,
- StringRef DocComment) {
+ llvm::StringRef DocComment) {
// Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
// information in the documentation field.
std::string Result;
diff --git a/clang-tools-extra/clangd/Compiler.cpp b/clang-tools-extra/clangd/Compiler.cpp
index 011841c4613..c94ef75522e 100644
--- a/clang-tools-extra/clangd/Compiler.cpp
+++ b/clang-tools-extra/clangd/Compiler.cpp
@@ -14,21 +14,20 @@
#include "llvm/Support/Format.h"
#include "llvm/Support/FormatVariadic.h"
-using namespace llvm;
namespace clang {
namespace clangd {
void IgnoreDiagnostics::log(DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &Info) {
// FIXME: format lazily, in case vlog is off.
- SmallString<64> Message;
+ llvm::SmallString<64> Message;
Info.FormatDiagnostic(Message);
- SmallString<64> Location;
+ llvm::SmallString<64> Location;
if (Info.hasSourceManager() && Info.getLocation().isValid()) {
auto &SourceMgr = Info.getSourceManager();
auto Loc = SourceMgr.getFileLoc(Info.getLocation());
- raw_svector_ostream OS(Location);
+ llvm::raw_svector_ostream OS(Location);
Loc.print(OS, SourceMgr);
OS << ":";
}
@@ -41,11 +40,13 @@ void IgnoreDiagnostics::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
IgnoreDiagnostics::log(DiagLevel, Info);
}
-std::unique_ptr<CompilerInstance> prepareCompilerInstance(
- std::unique_ptr<clang::CompilerInvocation> CI,
- const PrecompiledPreamble *Preamble, std::unique_ptr<MemoryBuffer> Buffer,
- std::shared_ptr<PCHContainerOperations> PCHs,
- IntrusiveRefCntPtr<vfs::FileSystem> VFS, DiagnosticConsumer &DiagsClient) {
+std::unique_ptr<CompilerInstance>
+prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,
+ const PrecompiledPreamble *Preamble,
+ std::unique_ptr<llvm::MemoryBuffer> Buffer,
+ std::shared_ptr<PCHContainerOperations> PCHs,
+ llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
+ DiagnosticConsumer &DiagsClient) {
assert(VFS && "VFS is null");
assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
"Setting RetainRemappedFileBuffers to true will cause a memory leak "
diff --git a/clang-tools-extra/clangd/Diagnostics.cpp b/clang-tools-extra/clangd/Diagnostics.cpp
index ca43be8410c..1cd52ad3475 100644
--- a/clang-tools-extra/clangd/Diagnostics.cpp
+++ b/clang-tools-extra/clangd/Diagnostics.cpp
@@ -17,7 +17,6 @@
#include "llvm/Support/Path.h"
#include <algorithm>
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -57,7 +56,7 @@ Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
if (locationInRange(Loc, R, M))
return halfOpenToRange(M, R);
}
- Optional<Range> FallbackRange;
+ llvm::Optional<Range> FallbackRange;
// The range may be given as a fixit hint instead.
for (const auto &F : D.getFixItHints()) {
auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
@@ -93,7 +92,7 @@ bool isNote(DiagnosticsEngine::Level L) {
return L == DiagnosticsEngine::Note || L == DiagnosticsEngine::Remark;
}
-StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
+llvm::StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
switch (Lvl) {
case DiagnosticsEngine::Ignored:
return "ignored";
@@ -122,12 +121,12 @@ StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
///
/// dir1/dir2/dir3/../../dir4/header.h:12:23
/// error: undeclared identifier
-void printDiag(raw_string_ostream &OS, const DiagBase &D) {
+void printDiag(llvm::raw_string_ostream &OS, const DiagBase &D) {
if (D.InsideMainFile) {
// Paths to main files are often taken from compile_command.json, where they
// are typically absolute. To reduce noise we print only basename for them,
// it should not be confusing and saves space.
- OS << sys::path::filename(D.File) << ":";
+ OS << llvm::sys::path::filename(D.File) << ":";
} else {
OS << D.File << ":";
}
@@ -147,7 +146,7 @@ void printDiag(raw_string_ostream &OS, const DiagBase &D) {
/// Capitalizes the first word in the diagnostic's message.
std::string capitalize(std::string Message) {
if (!Message.empty())
- Message[0] = toUpper(Message[0]);
+ Message[0] = llvm::toUpper(Message[0]);
return Message;
}
@@ -165,7 +164,7 @@ std::string capitalize(std::string Message) {
/// note: candidate function not viable: requires 3 arguments
std::string mainMessage(const Diag &D) {
std::string Result;
- raw_string_ostream OS(Result);
+ llvm::raw_string_ostream OS(Result);
OS << D.Message;
for (auto &Note : D.Notes) {
OS << "\n\n";
@@ -180,7 +179,7 @@ std::string mainMessage(const Diag &D) {
/// for the user to understand the note.
std::string noteMessage(const Diag &Main, const DiagBase &Note) {
std::string Result;
- raw_string_ostream OS(Result);
+ llvm::raw_string_ostream OS(Result);
OS << Note.Message;
OS << "\n\n";
printDiag(OS, Main);
@@ -189,7 +188,7 @@ std::string noteMessage(const Diag &Main, const DiagBase &Note) {
}
} // namespace
-raw_ostream &operator<<(raw_ostream &OS, const DiagBase &D) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const DiagBase &D) {
OS << "[";
if (!D.InsideMainFile)
OS << D.File << ":";
@@ -198,7 +197,7 @@ raw_ostream &operator<<(raw_ostream &OS, const DiagBase &D) {
return OS << D.Message;
}
-raw_ostream &operator<<(raw_ostream &OS, const Fix &F) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Fix &F) {
OS << F.Message << " {";
const char *Sep = "";
for (const auto &Edit : F.Edits) {
@@ -208,7 +207,7 @@ raw_ostream &operator<<(raw_ostream &OS, const Fix &F) {
return OS << "}";
}
-raw_ostream &operator<<(raw_ostream &OS, const Diag &D) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diag &D) {
OS << static_cast<const DiagBase &>(D);
if (!D.Notes.empty()) {
OS << ", notes: {";
@@ -240,9 +239,9 @@ CodeAction toCodeAction(const Fix &F, const URIForFile &File) {
return Action;
}
-void toLSPDiags(const Diag &D, const URIForFile &File,
- const ClangdDiagnosticOptions &Opts,
- function_ref<void(clangd::Diagnostic, ArrayRef<Fix>)> OutFn) {
+void toLSPDiags(
+ const Diag &D, const URIForFile &File, const ClangdDiagnosticOptions &Opts,
+ llvm::function_ref<void(clangd::Diagnostic, llvm::ArrayRef<Fix>)> OutFn) {
auto FillBasicFields = [](const DiagBase &D) -> clangd::Diagnostic {
clangd::Diagnostic Res;
Res.range = D.Range;
@@ -269,7 +268,7 @@ void toLSPDiags(const Diag &D, const URIForFile &File,
continue;
clangd::Diagnostic Res = FillBasicFields(Note);
Res.message = noteMessage(D, Note);
- OutFn(std::move(Res), ArrayRef<Fix>());
+ OutFn(std::move(Res), llvm::ArrayRef<Fix>());
}
}
@@ -315,7 +314,7 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
auto FillDiagBase = [&](DiagBase &D) {
D.Range = diagnosticRange(Info, *LangOpts);
- SmallString<64> Message;
+ llvm::SmallString<64> Message;
Info.FormatDiagnostic(Message);
D.Message = Message.str();
D.InsideMainFile = InsideMainFile;
@@ -333,7 +332,7 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
if (!InsideMainFile)
return false;
- SmallVector<TextEdit, 1> Edits;
+ llvm::SmallVector<TextEdit, 1> Edits;
for (auto &FixIt : Info.getFixItHints()) {
if (!isInsideMainFile(FixIt.RemoveRange.getBegin(),
Info.getSourceManager()))
@@ -341,16 +340,16 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
Edits.push_back(toTextEdit(FixIt, Info.getSourceManager(), *LangOpts));
}
- SmallString<64> Message;
+ llvm::SmallString<64> Message;
// If requested and possible, create a message like "change 'foo' to 'bar'".
if (SyntheticMessage && Info.getNumFixItHints() == 1) {
const auto &FixIt = Info.getFixItHint(0);
bool Invalid = false;
- StringRef Remove = Lexer::getSourceText(
+ llvm::StringRef Remove = Lexer::getSourceText(
FixIt.RemoveRange, Info.getSourceManager(), *LangOpts, &Invalid);
- StringRef Insert = FixIt.CodeToInsert;
+ llvm::StringRef Insert = FixIt.CodeToInsert;
if (!Invalid) {
- raw_svector_ostream M(Message);
+ llvm::raw_svector_ostream M(Message);
if (!Remove.empty() && !Insert.empty())
M << "change '" << Remove << "' to '" << Insert << "'";
else if (!Remove.empty())
diff --git a/clang-tools-extra/clangd/DraftStore.cpp b/clang-tools-extra/clangd/DraftStore.cpp
index b5bcda814c4..9b6c1fc4052 100644
--- a/clang-tools-extra/clangd/DraftStore.cpp
+++ b/clang-tools-extra/clangd/DraftStore.cpp
@@ -11,11 +11,10 @@
#include "SourceCode.h"
#include "llvm/Support/Errc.h"
-using namespace llvm;
namespace clang {
namespace clangd {
-Optional<std::string> DraftStore::getDraft(PathRef File) const {
+llvm::Optional<std::string> DraftStore::getDraft(PathRef File) const {
std::lock_guard<std::mutex> Lock(Mutex);
auto It = Drafts.find(File);
@@ -35,20 +34,19 @@ std::vector<Path> DraftStore::getActiveFiles() const {
return ResultVector;
}
-void DraftStore::addDraft(PathRef File, StringRef Contents) {
+void DraftStore::addDraft(PathRef File, llvm::StringRef Contents) {
std::lock_guard<std::mutex> Lock(Mutex);
Drafts[File] = Contents;
}
-Expected<std::string>
-DraftStore::updateDraft(PathRef File,
- ArrayRef<TextDocumentContentChangeEvent> Changes) {
+llvm::Expected<std::string> DraftStore::updateDraft(
+ PathRef File, llvm::ArrayRef<TextDocumentContentChangeEvent> Changes) {
std::lock_guard<std::mutex> Lock(Mutex);
auto EntryIt = Drafts.find(File);
if (EntryIt == Drafts.end()) {
- return make_error<StringError>(
+ return llvm::make_error<llvm::StringError>(
"Trying to do incremental update on non-added document: " + File,
llvm::errc::invalid_argument);
}
@@ -62,19 +60,21 @@ DraftStore::updateDraft(PathRef File,
}
const Position &Start = Change.range->start;
- Expected<size_t> StartIndex = positionToOffset(Contents, Start, false);
+ llvm::Expected<size_t> StartIndex =
+ positionToOffset(Contents, Start, false);
if (!StartIndex)
return StartIndex.takeError();
const Position &End = Change.range->end;
- Expected<size_t> EndIndex = positionToOffset(Contents, End, false);
+ llvm::Expected<size_t> EndIndex = positionToOffset(Contents, End, false);
if (!EndIndex)
return EndIndex.takeError();
if (*EndIndex < *StartIndex)
- return make_error<StringError>(
- formatv("Range's end position ({0}) is before start position ({1})",
- End, Start),
+ return llvm::make_error<llvm::StringError>(
+ llvm::formatv(
+ "Range's end position ({0}) is before start position ({1})", End,
+ Start),
llvm::errc::invalid_argument);
// Since the range length between two LSP positions is dependent on the
@@ -88,10 +88,10 @@ DraftStore::updateDraft(PathRef File,
lspLength(Contents.substr(*StartIndex, *EndIndex - *StartIndex));
if (Change.rangeLength && ComputedRangeLength != *Change.rangeLength)
- return make_error<StringError>(
- formatv("Change's rangeLength ({0}) doesn't match the "
- "computed range length ({1}).",
- *Change.rangeLength, *EndIndex - *StartIndex),
+ return llvm::make_error<llvm::StringError>(
+ llvm::formatv("Change's rangeLength ({0}) doesn't match the "
+ "computed range length ({1}).",
+ *Change.rangeLength, *EndIndex - *StartIndex),
llvm::errc::invalid_argument);
std::string NewContents;
diff --git a/clang-tools-extra/clangd/ExpectedTypes.cpp b/clang-tools-extra/clangd/ExpectedTypes.cpp
index 5c9cec89c26..4bbf0651260 100644
--- a/clang-tools-extra/clangd/ExpectedTypes.cpp
+++ b/clang-tools-extra/clangd/ExpectedTypes.cpp
@@ -5,8 +5,6 @@
#include "clang/Sema/CodeCompleteConsumer.h"
#include "llvm/ADT/STLExtras.h"
-using namespace llvm;
-
namespace clang {
namespace clangd {
namespace {
@@ -33,7 +31,8 @@ static const Type *toEquivClass(ASTContext &Ctx, QualType T) {
return T.getTypePtr();
}
-static Optional<QualType> typeOfCompletion(const CodeCompletionResult &R) {
+static llvm::Optional<QualType>
+typeOfCompletion(const CodeCompletionResult &R) {
auto *VD = dyn_cast_or_null<ValueDecl>(R.Declaration);
if (!VD)
return None; // We handle only variables and functions below.
@@ -49,13 +48,13 @@ static Optional<QualType> typeOfCompletion(const CodeCompletionResult &R) {
}
} // namespace
-Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
+llvm::Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
if (T.isNull())
return None;
const Type *C = toEquivClass(Ctx, T);
if (!C)
return None;
- SmallString<128> Encoded;
+ llvm::SmallString<128> Encoded;
if (index::generateUSRForType(QualType(C, 0), Ctx, Encoded))
return None;
return OpaqueType(Encoded.str());
@@ -63,11 +62,12 @@ Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
OpaqueType::OpaqueType(std::string Data) : Data(std::move(Data)) {}
-Optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx, QualType Type) {
+llvm::Optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx,
+ QualType Type) {
return encode(Ctx, Type);
}
-Optional<OpaqueType>
+llvm::Optional<OpaqueType>
OpaqueType::fromCompletionResult(ASTContext &Ctx,
const CodeCompletionResult &R) {
auto T = typeOfCompletion(R);
diff --git a/clang-tools-extra/clangd/FS.cpp b/clang-tools-extra/clangd/FS.cpp
index e588e00bb77..5d690c86f6b 100644
--- a/clang-tools-extra/clangd/FS.cpp
+++ b/clang-tools-extra/clangd/FS.cpp
@@ -12,17 +12,17 @@
#include "llvm/ADT/None.h"
#include "llvm/Support/Path.h"
-using namespace llvm;
namespace clang {
namespace clangd {
-PreambleFileStatusCache::PreambleFileStatusCache(StringRef MainFilePath)
+PreambleFileStatusCache::PreambleFileStatusCache(llvm::StringRef MainFilePath)
: MainFilePath(MainFilePath) {
- assert(sys::path::is_absolute(MainFilePath));
+ assert(llvm::sys::path::is_absolute(MainFilePath));
}
-void PreambleFileStatusCache::update(const vfs::FileSystem &FS, vfs::Status S) {
- SmallString<32> PathStore(S.getName());
+void PreambleFileStatusCache::update(const llvm::vfs::FileSystem &FS,
+ llvm::vfs::Status S) {
+ llvm::SmallString<32> PathStore(S.getName());
if (FS.makeAbsolute(PathStore))
return;
// Do not cache status for the main file.
@@ -32,25 +32,27 @@ void PreambleFileStatusCache::update(const vfs::FileSystem &FS, vfs::Status S) {
StatCache.insert({PathStore, std::move(S)});
}
-Optional<vfs::Status> PreambleFileStatusCache::lookup(StringRef File) const {
+llvm::Optional<llvm::vfs::Status>
+PreambleFileStatusCache::lookup(llvm::StringRef File) const {
auto I = StatCache.find(File);
if (I != StatCache.end())
return I->getValue();
return None;
}
-IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getProducingFS(
- IntrusiveRefCntPtr<vfs::FileSystem> FS) {
+llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
+PreambleFileStatusCache::getProducingFS(
+ llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) {
// This invalidates old status in cache if files are re-`open()`ed or
// re-`stat()`ed in case file status has changed during preamble build.
- class CollectFS : public vfs::ProxyFileSystem {
+ class CollectFS : public llvm::vfs::ProxyFileSystem {
public:
- CollectFS(IntrusiveRefCntPtr<vfs::FileSystem> FS,
+ CollectFS(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
PreambleFileStatusCache &StatCache)
: ProxyFileSystem(std::move(FS)), StatCache(StatCache) {}
- ErrorOr<std::unique_ptr<vfs::File>>
- openFileForRead(const Twine &Path) override {
+ llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
+ openFileForRead(const llvm::Twine &Path) override {
auto File = getUnderlyingFS().openFileForRead(Path);
if (!File || !*File)
return File;
@@ -64,7 +66,7 @@ IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getProducingFS(
return File;
}
- ErrorOr<vfs::Status> status(const Twine &Path) override {
+ llvm::ErrorOr<llvm::vfs::Status> status(const llvm::Twine &Path) override {
auto S = getUnderlyingFS().status(Path);
if (S)
StatCache.update(getUnderlyingFS(), *S);
@@ -74,18 +76,20 @@ IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getProducingFS(
private:
PreambleFileStatusCache &StatCache;
};
- return IntrusiveRefCntPtr<CollectFS>(new CollectFS(std::move(FS), *this));
+ return llvm::IntrusiveRefCntPtr<CollectFS>(
+ new CollectFS(std::move(FS), *this));
}
-IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getConsumingFS(
- IntrusiveRefCntPtr<vfs::FileSystem> FS) const {
- class CacheVFS : public vfs::ProxyFileSystem {
+llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
+PreambleFileStatusCache::getConsumingFS(
+ llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) const {
+ class CacheVFS : public llvm::vfs::ProxyFileSystem {
public:
- CacheVFS(IntrusiveRefCntPtr<vfs::FileSystem> FS,
+ CacheVFS(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
const PreambleFileStatusCache &StatCache)
: ProxyFileSystem(std::move(FS)), StatCache(StatCache) {}
- ErrorOr<vfs::Status> status(const Twine &Path) override {
+ llvm::ErrorOr<llvm::vfs::Status> status(const llvm::Twine &Path) override {
if (auto S = StatCache.lookup(Path.str()))
return *S;
return getUnderlyingFS().status(Path);
@@ -94,7 +98,7 @@ IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getConsumingFS(
private:
const PreambleFileStatusCache &StatCache;
};
- return IntrusiveRefCntPtr<CacheVFS>(new CacheVFS(std::move(FS), *this));
+ return llvm::IntrusiveRefCntPtr<CacheVFS>(new CacheVFS(std::move(FS), *this));
}
} // namespace clangd
diff --git a/clang-tools-extra/clangd/FSProvider.cpp b/clang-tools-extra/clangd/FSProvider.cpp
index 99e7596e83a..794bb82592b 100644
--- a/clang-tools-extra/clangd/FSProvider.cpp
+++ b/clang-tools-extra/clangd/FSProvider.cpp
@@ -15,8 +15,6 @@
#include "llvm/Support/VirtualFileSystem.h"
#include <memory>
-using namespace llvm;
-
namespace clang {
namespace clangd {
@@ -28,9 +26,9 @@ public:
explicit VolatileFileSystem(llvm::IntrusiveRefCntPtr<FileSystem> FS)
: ProxyFileSystem(std::move(FS)) {}
- llvm::ErrorOr<std::unique_ptr<vfs::File>>
- openFileForRead(const Twine &InPath) override {
- SmallString<128> Path;
+ llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
+ openFileForRead(const llvm::Twine &InPath) override {
+ llvm::SmallString<128> Path;
InPath.toVector(Path);
auto File = getUnderlyingFS().openFileForRead(Path);
@@ -38,28 +36,30 @@ public:
return File;
// Try to guess preamble files, they can be memory-mapped even on Windows as
// clangd has exclusive access to those.
- StringRef FileName = llvm::sys::path::filename(Path);
+ llvm::StringRef FileName = llvm::sys::path::filename(Path);
if (FileName.startswith("preamble-") && FileName.endswith(".pch"))
return File;
return std::unique_ptr<VolatileFile>(new VolatileFile(std::move(*File)));
}
private:
- class VolatileFile : public vfs::File {
+ class VolatileFile : public llvm::vfs::File {
public:
- VolatileFile(std::unique_ptr<vfs::File> Wrapped)
+ VolatileFile(std::unique_ptr<llvm::vfs::File> Wrapped)
: Wrapped(std::move(Wrapped)) {
assert(this->Wrapped);
}
virtual llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
- getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
- bool /*IsVolatile*/) override {
+ getBuffer(const llvm::Twine &Name, int64_t FileSize,
+ bool RequiresNullTerminator, bool /*IsVolatile*/) override {
return Wrapped->getBuffer(Name, FileSize, RequiresNullTerminator,
/*IsVolatile=*/true);
}
- llvm::ErrorOr<vfs::Status> status() override { return Wrapped->status(); }
+ llvm::ErrorOr<llvm::vfs::Status> status() override {
+ return Wrapped->status();
+ }
llvm::ErrorOr<std::string> getName() override { return Wrapped->getName(); }
std::error_code close() override { return Wrapped->close(); }
@@ -77,7 +77,7 @@ clang::clangd::RealFileSystemProvider::getFileSystem() const {
#ifdef _WIN32
return new VolatileFileSystem(vfs::getRealFileSystem());
#else
- return vfs::getRealFileSystem();
+ return llvm::vfs::getRealFileSystem();
#endif
}
} // namespace clangd
diff --git a/clang-tools-extra/clangd/FileDistance.cpp b/clang-tools-extra/clangd/FileDistance.cpp
index 6bd73e526c3..7bac2516707 100644
--- a/clang-tools-extra/clangd/FileDistance.cpp
+++ b/clang-tools-extra/clangd/FileDistance.cpp
@@ -36,7 +36,6 @@
#include "llvm/ADT/STLExtras.h"
#include <queue>
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -45,21 +44,23 @@ namespace clangd {
// C:\foo\bar --> /c:/foo/bar
// /foo/ --> /foo
// a/b/c --> /a/b/c
-static SmallString<128> canonicalize(StringRef Path) {
- SmallString<128> Result = Path.rtrim('/');
- native(Result, sys::path::Style::posix);
+static llvm::SmallString<128> canonicalize(llvm::StringRef Path) {
+ llvm::SmallString<128> Result = Path.rtrim('/');
+ native(Result, llvm::sys::path::Style::posix);
if (Result.empty() || Result.front() != '/')
Result.insert(Result.begin(), '/');
return Result;
}
constexpr const unsigned FileDistance::Unreachable;
-const hash_code FileDistance::RootHash = hash_value(StringRef("/"));
+const llvm::hash_code FileDistance::RootHash =
+ llvm::hash_value(llvm::StringRef("/"));
-FileDistance::FileDistance(StringMap<SourceParams> Sources,
+FileDistance::FileDistance(llvm::StringMap<SourceParams> Sources,
const FileDistanceOptions &Opts)
: Opts(Opts) {
- DenseMap<hash_code, SmallVector<hash_code, 4>> DownEdges;
+ llvm::DenseMap<llvm::hash_code, llvm::SmallVector<llvm::hash_code, 4>>
+ DownEdges;
// Compute the best distance following only up edges.
// Keep track of down edges, in case we can use them to improve on this.
for (const auto &S : Sources) {
@@ -67,13 +68,13 @@ FileDistance::FileDistance(StringMap<SourceParams> Sources,
dlog("Source {0} = {1}, MaxUp = {2}", Canonical, S.second.Cost,
S.second.MaxUpTraversals);
// Walk up to ancestors of this source, assigning cost.
- StringRef Rest = Canonical;
- hash_code Hash = hash_value(Rest);
+ llvm::StringRef Rest = Canonical;
+ llvm::hash_code Hash = llvm::hash_value(Rest);
for (unsigned I = 0; !Rest.empty(); ++I) {
- Rest = parent_path(Rest, sys::path::Style::posix);
- auto NextHash = hash_value(Rest);
+ Rest = parent_path(Rest, llvm::sys::path::Style::posix);
+ auto NextHash = llvm::hash_value(Rest);
auto &Down = DownEdges[NextHash];
- if (!is_contained(Down, Hash))
+ if (!llvm::is_contained(Down, Hash))
Down.push_back(Hash);
// We can't just break after MaxUpTraversals, must still set DownEdges.
if (I > S.getValue().MaxUpTraversals) {
@@ -96,8 +97,8 @@ FileDistance::FileDistance(StringMap<SourceParams> Sources,
}
// Now propagate scores parent -> child if that's an improvement.
// BFS ensures we propagate down chains (must visit parents before children).
- std::queue<hash_code> Next;
- for (auto Child : DownEdges.lookup(hash_value(StringRef(""))))
+ std::queue<llvm::hash_code> Next;
+ for (auto Child : DownEdges.lookup(llvm::hash_value(llvm::StringRef(""))))
Next.push(Child);
while (!Next.empty()) {
auto Parent = Next.front();
@@ -115,14 +116,14 @@ FileDistance::FileDistance(StringMap<SourceParams> Sources,
}
}
-unsigned FileDistance::distance(StringRef Path) {
+unsigned FileDistance::distance(llvm::StringRef Path) {
auto Canonical = canonicalize(Path);
unsigned Cost = Unreachable;
- SmallVector<hash_code, 16> Ancestors;
+ llvm::SmallVector<llvm::hash_code, 16> Ancestors;
// Walk up ancestors until we find a path we know the distance for.
- for (StringRef Rest = Canonical; !Rest.empty();
- Rest = parent_path(Rest, sys::path::Style::posix)) {
- auto Hash = hash_value(Rest);
+ for (llvm::StringRef Rest = Canonical; !Rest.empty();
+ Rest = parent_path(Rest, llvm::sys::path::Style::posix)) {
+ auto Hash = llvm::hash_value(Rest);
if (Hash == RootHash && !Ancestors.empty() &&
!Opts.AllowDownTraversalFromRoot) {
Cost = Unreachable;
@@ -137,7 +138,7 @@ unsigned FileDistance::distance(StringRef Path) {
}
// Now we know the costs for (known node, queried node].
// Fill these in, walking down the directory tree.
- for (hash_code Hash : reverse(Ancestors)) {
+ for (llvm::hash_code Hash : llvm::reverse(Ancestors)) {
if (Cost != Unreachable)
Cost += Opts.DownCost;
Cache.try_emplace(Hash, Cost);
@@ -146,8 +147,8 @@ unsigned FileDistance::distance(StringRef Path) {
return Cost;
}
-unsigned URIDistance::distance(StringRef URI) {
- auto R = Cache.try_emplace(hash_value(URI), FileDistance::Unreachable);
+unsigned URIDistance::distance(llvm::StringRef URI) {
+ auto R = Cache.try_emplace(llvm::hash_value(URI), FileDistance::Unreachable);
if (!R.second)
return R.first->getSecond();
if (auto U = clangd::URI::parse(URI)) {
@@ -159,15 +160,15 @@ unsigned URIDistance::distance(StringRef URI) {
return R.first->second;
}
-FileDistance &URIDistance::forScheme(StringRef Scheme) {
+FileDistance &URIDistance::forScheme(llvm::StringRef Scheme) {
auto &Delegate = ByScheme[Scheme];
if (!Delegate) {
- StringMap<SourceParams> SchemeSources;
+ llvm::StringMap<SourceParams> SchemeSources;
for (const auto &Source : Sources) {
if (auto U = clangd::URI::create(Source.getKey(), Scheme))
SchemeSources.try_emplace(U->body(), Source.getValue());
else
- consumeError(U.takeError());
+ llvm::consumeError(U.takeError());
}
dlog("FileDistance for scheme {0}: {1}/{2} sources", Scheme,
SchemeSources.size(), Sources.size());
@@ -176,21 +177,23 @@ FileDistance &URIDistance::forScheme(StringRef Scheme) {
return *Delegate;
}
-static std::pair<std::string, int> scopeToPath(StringRef Scope) {
- SmallVector<StringRef, 4> Split;
+static std::pair<std::string, int> scopeToPath(llvm::StringRef Scope) {
+ llvm::SmallVector<llvm::StringRef, 4> Split;
Scope.split(Split, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
- return {"/" + join(Split, "/"), Split.size()};
+ return {"/" + llvm::join(Split, "/"), Split.size()};
}
-static FileDistance createScopeFileDistance(ArrayRef<std::string> QueryScopes) {
+static FileDistance
+createScopeFileDistance(llvm::ArrayRef<std::string> QueryScopes) {
FileDistanceOptions Opts;
Opts.UpCost = 2;
Opts.DownCost = 4;
Opts.AllowDownTraversalFromRoot = false;
- StringMap<SourceParams> Sources;
- StringRef Preferred = QueryScopes.empty() ? "" : QueryScopes.front().c_str();
- for (StringRef S : QueryScopes) {
+ llvm::StringMap<SourceParams> Sources;
+ llvm::StringRef Preferred =
+ QueryScopes.empty() ? "" : QueryScopes.front().c_str();
+ for (llvm::StringRef S : QueryScopes) {
SourceParams Param;
// Penalize the global scope even it's preferred, as all projects can define
// symbols in it, and there is pattern where using-namespace is used in
@@ -209,10 +212,10 @@ static FileDistance createScopeFileDistance(ArrayRef<std::string> QueryScopes) {
return FileDistance(Sources, Opts);
}
-ScopeDistance::ScopeDistance(ArrayRef<std::string> QueryScopes)
+ScopeDistance::ScopeDistance(llvm::ArrayRef<std::string> QueryScopes)
: Distance(createScopeFileDistance(QueryScopes)) {}
-unsigned ScopeDistance::distance(StringRef SymbolScope) {
+unsigned ScopeDistance::distance(llvm::StringRef SymbolScope) {
return Distance.distance(scopeToPath(SymbolScope).first);
}
diff --git a/clang-tools-extra/clangd/FindSymbols.cpp b/clang-tools-extra/clangd/FindSymbols.cpp
index 92769bb317b..208e78c65b9 100644
--- a/clang-tools-extra/clangd/FindSymbols.cpp
+++ b/clang-tools-extra/clangd/FindSymbols.cpp
@@ -25,7 +25,6 @@
#define DEBUG_TYPE "FindSymbols"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -100,9 +99,9 @@ struct ScoredSymbolGreater {
} // namespace
-Expected<std::vector<SymbolInformation>>
-getWorkspaceSymbols(StringRef Query, int Limit, const SymbolIndex *const Index,
- StringRef HintPath) {
+llvm::Expected<std::vector<SymbolInformation>>
+getWorkspaceSymbols(llvm::StringRef Query, int Limit,
+ const SymbolIndex *const Index, llvm::StringRef HintPath) {
std::vector<SymbolInformation> Result;
if (Query.empty() || !Index)
return Result;
@@ -153,7 +152,7 @@ getWorkspaceSymbols(StringRef Query, int Limit, const SymbolIndex *const Index,
L.range = {Start, End};
SymbolKind SK = indexSymbolKindToSymbolKind(Sym.SymInfo.Kind);
std::string Scope = Sym.Scope;
- StringRef ScopeRef = Scope;
+ llvm::StringRef ScopeRef = Scope;
ScopeRef.consume_back("::");
SymbolInformation Info = {Sym.Name, SK, L, ScopeRef};
diff --git a/clang-tools-extra/clangd/FuzzyMatch.cpp b/clang-tools-extra/clangd/FuzzyMatch.cpp
index c16712faad5..433242e6a35 100644
--- a/clang-tools-extra/clangd/FuzzyMatch.cpp
+++ b/clang-tools-extra/clangd/FuzzyMatch.cpp
@@ -60,7 +60,6 @@
#include "llvm/ADT/Optional.h"
#include "llvm/Support/Format.h"
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -75,7 +74,7 @@ static constexpr int AwfulScore = -(1 << 13);
static bool isAwful(int S) { return S < AwfulScore / 2; }
static constexpr int PerfectBonus = 3; // Perfect per-pattern-char score.
-FuzzyMatcher::FuzzyMatcher(StringRef Pattern)
+FuzzyMatcher::FuzzyMatcher(llvm::StringRef Pattern)
: PatN(std::min<int>(MaxPat, Pattern.size())),
ScoreScale(PatN ? float{1} / (PerfectBonus * PatN) : 0), WordN(0) {
std::copy(Pattern.begin(), Pattern.begin() + PatN, Pat);
@@ -87,20 +86,20 @@ FuzzyMatcher::FuzzyMatcher(StringRef Pattern)
for (int W = 0; W < P; ++W)
for (Action A : {Miss, Match})
Scores[P][W][A] = {AwfulScore, Miss};
- PatTypeSet =
- calculateRoles(StringRef(Pat, PatN), makeMutableArrayRef(PatRole, PatN));
+ PatTypeSet = calculateRoles(llvm::StringRef(Pat, PatN),
+ llvm::makeMutableArrayRef(PatRole, PatN));
}
-Optional<float> FuzzyMatcher::match(StringRef Word) {
+llvm::Optional<float> FuzzyMatcher::match(llvm::StringRef Word) {
if (!(WordContainsPattern = init(Word)))
- return None;
+ return llvm::None;
if (!PatN)
return 1;
buildGraph();
auto Best = std::max(Scores[PatN][WordN][Miss].Score,
Scores[PatN][WordN][Match].Score);
if (isAwful(Best))
- return None;
+ return llvm::None;
float Score =
ScoreScale * std::min(PerfectBonus * PatN, std::max<int>(0, Best));
// If the pattern is as long as the word, we have an exact string match,
@@ -153,7 +152,8 @@ constexpr static uint8_t CharRoles[] = {
template <typename T> static T packedLookup(const uint8_t *Data, int I) {
return static_cast<T>((Data[I >> 2] >> ((I & 3) * 2)) & 3);
}
-CharTypeSet calculateRoles(StringRef Text, MutableArrayRef<CharRole> Roles) {
+CharTypeSet calculateRoles(llvm::StringRef Text,
+ llvm::MutableArrayRef<CharRole> Roles) {
assert(Text.size() == Roles.size());
if (Text.size() == 0)
return 0;
@@ -179,7 +179,7 @@ CharTypeSet calculateRoles(StringRef Text, MutableArrayRef<CharRole> Roles) {
// Sets up the data structures matching Word.
// Returns false if we can cheaply determine that no match is possible.
-bool FuzzyMatcher::init(StringRef NewWord) {
+bool FuzzyMatcher::init(llvm::StringRef NewWord) {
WordN = std::min<int>(MaxWord, NewWord.size());
if (PatN > WordN)
return false;
@@ -200,8 +200,8 @@ bool FuzzyMatcher::init(StringRef NewWord) {
// FIXME: some words are hard to tokenize algorithmically.
// e.g. vsprintf is V S Print F, and should match [pri] but not [int].
// We could add a tokenization dictionary for common stdlib names.
- WordTypeSet = calculateRoles(StringRef(Word, WordN),
- makeMutableArrayRef(WordRole, WordN));
+ WordTypeSet = calculateRoles(llvm::StringRef(Word, WordN),
+ llvm::makeMutableArrayRef(WordRole, WordN));
return true;
}
@@ -299,13 +299,13 @@ int FuzzyMatcher::matchBonus(int P, int W, Action Last) const {
return S;
}
-SmallString<256> FuzzyMatcher::dumpLast(raw_ostream &OS) const {
- SmallString<256> Result;
- OS << "=== Match \"" << StringRef(Word, WordN) << "\" against ["
- << StringRef(Pat, PatN) << "] ===\n";
+llvm::SmallString<256> FuzzyMatcher::dumpLast(llvm::raw_ostream &OS) const {
+ llvm::SmallString<256> Result;
+ OS << "=== Match \"" << llvm::StringRef(Word, WordN) << "\" against ["
+ << llvm::StringRef(Pat, PatN) << "] ===\n";
if (PatN == 0) {
OS << "Pattern is empty: perfect match.\n";
- return Result = StringRef(Word, WordN);
+ return Result = llvm::StringRef(Word, WordN);
}
if (WordN == 0) {
OS << "Word is empty: no match.\n";
@@ -349,28 +349,28 @@ SmallString<256> FuzzyMatcher::dumpLast(raw_ostream &OS) const {
if (A[WordN - 1] == Match)
Result.push_back(']');
- for (char C : StringRef(Word, WordN))
+ for (char C : llvm::StringRef(Word, WordN))
OS << " " << C << " ";
OS << "\n";
for (int I = 0, J = 0; I < WordN; I++)
OS << " " << (A[I] == Match ? Pat[J++] : ' ') << " ";
OS << "\n";
for (int I = 0; I < WordN; I++)
- OS << format("%2d ", S[I]);
+ OS << llvm::format("%2d ", S[I]);
OS << "\n";
OS << "\nSegmentation:";
- OS << "\n'" << StringRef(Word, WordN) << "'\n ";
+ OS << "\n'" << llvm::StringRef(Word, WordN) << "'\n ";
for (int I = 0; I < WordN; ++I)
OS << "?-+ "[static_cast<int>(WordRole[I])];
- OS << "\n[" << StringRef(Pat, PatN) << "]\n ";
+ OS << "\n[" << llvm::StringRef(Pat, PatN) << "]\n ";
for (int I = 0; I < PatN; ++I)
OS << "?-+ "[static_cast<int>(PatRole[I])];
OS << "\n";
OS << "\nScoring table (last-Miss, last-Match):\n";
OS << " | ";
- for (char C : StringRef(Word, WordN))
+ for (char C : llvm::StringRef(Word, WordN))
OS << " " << C << " ";
OS << "\n";
OS << "-+----" << std::string(WordN * 4, '-') << "\n";
@@ -379,8 +379,8 @@ SmallString<256> FuzzyMatcher::dumpLast(raw_ostream &OS) const {
OS << ((I && A == Miss) ? Pat[I - 1] : ' ') << "|";
for (int J = 0; J <= WordN; ++J) {
if (!isAwful(Scores[I][J][A].Score))
- OS << format("%3d%c", Scores[I][J][A].Score,
- Scores[I][J][A].Prev == Match ? '*' : ' ');
+ OS << llvm::format("%3d%c", Scores[I][J][A].Score,
+ Scores[I][J][A].Prev == Match ? '*' : ' ');
else
OS << " ";
}
diff --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
index e7cbc7bcc86..c2fff7b20f3 100644
--- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -13,7 +13,6 @@
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -32,22 +31,24 @@ GlobalCompilationDatabase::getFallbackCommand(PathRef File) const {
std::vector<std::string> Argv = {getFallbackClangPath()};
// Clang treats .h files as C by default, resulting in unhelpful diagnostics.
// Parsing as Objective C++ is friendly to more cases.
- if (sys::path::extension(File) == ".h")
+ if (llvm::sys::path::extension(File) == ".h")
Argv.push_back("-xobjective-c++-header");
Argv.push_back(File);
- return tooling::CompileCommand(sys::path::parent_path(File),
- sys::path::filename(File), std::move(Argv),
+ return tooling::CompileCommand(llvm::sys::path::parent_path(File),
+ llvm::sys::path::filename(File),
+ std::move(Argv),
/*Output=*/"");
}
DirectoryBasedGlobalCompilationDatabase::
- DirectoryBasedGlobalCompilationDatabase(Optional<Path> CompileCommandsDir)
+ DirectoryBasedGlobalCompilationDatabase(
+ llvm::Optional<Path> CompileCommandsDir)
: CompileCommandsDir(std::move(CompileCommandsDir)) {}
DirectoryBasedGlobalCompilationDatabase::
~DirectoryBasedGlobalCompilationDatabase() = default;
-Optional<tooling::CompileCommand>
+llvm::Optional<tooling::CompileCommand>
DirectoryBasedGlobalCompilationDatabase::getCompileCommand(
PathRef File, ProjectInfo *Project) const {
if (auto CDB = getCDBForFile(File, Project)) {
@@ -77,7 +78,7 @@ DirectoryBasedGlobalCompilationDatabase::getCDBInDirLocked(PathRef Dir) const {
tooling::CompilationDatabase *
DirectoryBasedGlobalCompilationDatabase::getCDBForFile(
PathRef File, ProjectInfo *Project) const {
- namespace path = sys::path;
+ namespace path = llvm::sys::path;
assert((path::is_absolute(File, path::Style::posix) ||
path::is_absolute(File, path::Style::windows)) &&
"path must be absolute");
@@ -113,7 +114,7 @@ OverlayCDB::OverlayCDB(const GlobalCompilationDatabase *Base,
});
}
-Optional<tooling::CompileCommand>
+llvm::Optional<tooling::CompileCommand>
OverlayCDB::getCompileCommand(PathRef File, ProjectInfo *Project) const {
{
std::lock_guard<std::mutex> Lock(Mutex);
diff --git a/clang-tools-extra/clangd/Headers.cpp b/clang-tools-extra/clangd/Headers.cpp
index c43d72c4eb8..06f822b34fb 100644
--- a/clang-tools-extra/clangd/Headers.cpp
+++ b/clang-tools-extra/clangd/Headers.cpp
@@ -17,7 +17,6 @@
#include "clang/Lex/HeaderSearch.h"
#include "llvm/Support/Path.h"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -30,9 +29,10 @@ public:
// Record existing #includes - both written and resolved paths. Only #includes
// in the main file are collected.
void InclusionDirective(SourceLocation HashLoc, const Token & /*IncludeTok*/,
- StringRef FileName, bool IsAngled,
+ llvm::StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange, const FileEntry *File,
- StringRef /*SearchPath*/, StringRef /*RelativePath*/,
+ llvm::StringRef /*SearchPath*/,
+ llvm::StringRef /*RelativePath*/,
const Module * /*Imported*/,
SrcMgr::CharacteristicKind FileKind) override {
if (SM.isWrittenInMainFile(HashLoc)) {
@@ -65,13 +65,13 @@ private:
} // namespace
-bool isLiteralInclude(StringRef Include) {
+bool isLiteralInclude(llvm::StringRef Include) {
return Include.startswith("<") || Include.startswith("\"");
}
bool HeaderFile::valid() const {
return (Verbatim && isLiteralInclude(File)) ||
- (!Verbatim && sys::path::is_absolute(File));
+ (!Verbatim && llvm::sys::path::is_absolute(File));
}
std::unique_ptr<PPCallbacks>
@@ -80,9 +80,9 @@ collectIncludeStructureCallback(const SourceManager &SM,
return llvm::make_unique<RecordHeaders>(SM, Out);
}
-void IncludeStructure::recordInclude(StringRef IncludingName,
- StringRef IncludedName,
- StringRef IncludedRealName) {
+void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
+ llvm::StringRef IncludedName,
+ llvm::StringRef IncludedRealName) {
auto Child = fileIndex(IncludedName);
if (!IncludedRealName.empty() && RealPathNames[Child].empty())
RealPathNames[Child] = IncludedRealName;
@@ -90,19 +90,20 @@ void IncludeStructure::recordInclude(StringRef IncludingName,
IncludeChildren[Parent].push_back(Child);
}
-unsigned IncludeStructure::fileIndex(StringRef Name) {
+unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
if (R.second)
RealPathNames.emplace_back();
return R.first->getValue();
}
-StringMap<unsigned> IncludeStructure::includeDepth(StringRef Root) const {
+llvm::StringMap<unsigned>
+IncludeStructure::includeDepth(llvm::StringRef Root) const {
// Include depth 0 is the main file only.
- StringMap<unsigned> Result;
+ llvm::StringMap<unsigned> Result;
Result[Root] = 0;
std::vector<unsigned> CurrentLevel;
- DenseSet<unsigned> Seen;
+ llvm::DenseSet<unsigned> Seen;
auto It = NameToIndex.find(Root);
if (It != NameToIndex.end()) {
CurrentLevel.push_back(It->second);
@@ -142,7 +143,7 @@ bool IncludeInserter::shouldInsertInclude(
assert(DeclaringHeader.valid() && InsertedHeader.valid());
if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
return false;
- auto Included = [&](StringRef Header) {
+ auto Included = [&](llvm::StringRef Header) {
return IncludedHeaders.find(Header) != IncludedHeaders.end();
};
return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
@@ -164,8 +165,9 @@ IncludeInserter::calculateIncludePath(const HeaderFile &DeclaringHeader,
return Suggested;
}
-Optional<TextEdit> IncludeInserter::insert(StringRef VerbatimHeader) const {
- Optional<TextEdit> Edit = None;
+llvm::Optional<TextEdit>
+IncludeInserter::insert(llvm::StringRef VerbatimHeader) const {
+ llvm::Optional<TextEdit> Edit = None;
if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
VerbatimHeader.startswith("<")))
Edit = replacementToEdit(Code, *Insertion);
diff --git a/clang-tools-extra/clangd/JSONTransport.cpp b/clang-tools-extra/clangd/JSONTransport.cpp
index 83ef49b0324..7189b23c1b2 100644
--- a/clang-tools-extra/clangd/JSONTransport.cpp
+++ b/clang-tools-extra/clangd/JSONTransport.cpp
@@ -11,66 +11,68 @@
#include "Transport.h"
#include "llvm/Support/Errno.h"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
-json::Object encodeError(Error E) {
+llvm::json::Object encodeError(llvm::Error E) {
std::string Message;
ErrorCode Code = ErrorCode::UnknownErrorCode;
- if (Error Unhandled =
- handleErrors(std::move(E), [&](const LSPError &L) -> Error {
+ if (llvm::Error Unhandled = llvm::handleErrors(
+ std::move(E), [&](const LSPError &L) -> llvm::Error {
Message = L.Message;
Code = L.Code;
- return Error::success();
+ return llvm::Error::success();
}))
- Message = toString(std::move(Unhandled));
+ Message = llvm::toString(std::move(Unhandled));
- return json::Object{
+ return llvm::json::Object{
{"message", std::move(Message)},
{"code", int64_t(Code)},
};
}
-Error decodeError(const json::Object &O) {
+llvm::Error decodeError(const llvm::json::Object &O) {
std::string Msg = 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 llvm::make_error<LSPError>(std::move(Msg), ErrorCode(*Code));
+ return llvm::make_error<llvm::StringError>(std::move(Msg),
+ llvm::inconvertibleErrorCode());
}
class JSONTransport : public Transport {
public:
- JSONTransport(std::FILE *In, raw_ostream &Out, raw_ostream *InMirror,
- bool Pretty, JSONStreamStyle Style)
- : In(In), Out(Out), InMirror(InMirror ? *InMirror : nulls()),
+ JSONTransport(std::FILE *In, llvm::raw_ostream &Out,
+ llvm::raw_ostream *InMirror, bool Pretty, JSONStreamStyle Style)
+ : In(In), Out(Out), InMirror(InMirror ? *InMirror : llvm::nulls()),
Pretty(Pretty), Style(Style) {}
- void notify(StringRef Method, json::Value Params) override {
- sendMessage(json::Object{
+ void notify(llvm::StringRef Method, llvm::json::Value Params) override {
+ sendMessage(llvm::json::Object{
{"jsonrpc", "2.0"},
{"method", Method},
{"params", std::move(Params)},
});
}
- void call(StringRef Method, json::Value Params, json::Value ID) override {
- sendMessage(json::Object{
+ void call(llvm::StringRef Method, llvm::json::Value Params,
+ llvm::json::Value ID) override {
+ sendMessage(llvm::json::Object{
{"jsonrpc", "2.0"},
{"id", std::move(ID)},
{"method", Method},
{"params", std::move(Params)},
});
}
- void reply(json::Value ID, Expected<json::Value> Result) override {
+ void reply(llvm::json::Value ID,
+ llvm::Expected<llvm::json::Value> Result) override {
if (Result) {
- sendMessage(json::Object{
+ sendMessage(llvm::json::Object{
{"jsonrpc", "2.0"},
{"id", std::move(ID)},
{"result", std::move(*Result)},
});
} else {
- sendMessage(json::Object{
+ sendMessage(llvm::json::Object{
{"jsonrpc", "2.0"},
{"id", std::move(ID)},
{"error", encodeError(Result.takeError())},
@@ -78,33 +80,34 @@ public:
}
}
- Error loop(MessageHandler &Handler) override {
+ llvm::Error loop(MessageHandler &Handler) override {
while (!feof(In)) {
if (ferror(In))
- return errorCodeToError(std::error_code(errno, std::system_category()));
+ return llvm::errorCodeToError(
+ std::error_code(errno, std::system_category()));
if (auto JSON = readRawMessage()) {
- if (auto Doc = json::parse(*JSON)) {
+ if (auto Doc = llvm::json::parse(*JSON)) {
vlog(Pretty ? "<<< {0:2}\n" : "<<< {0}\n", *Doc);
if (!handleMessage(std::move(*Doc), Handler))
- return Error::success(); // we saw the "exit" notification.
+ return llvm::Error::success(); // we saw the "exit" notification.
} else {
// Parse error. Log the raw message.
vlog("<<< {0}\n", *JSON);
- elog("JSON parse error: {0}", toString(Doc.takeError()));
+ elog("JSON parse error: {0}", llvm::toString(Doc.takeError()));
}
}
}
- return errorCodeToError(std::make_error_code(std::errc::io_error));
+ return llvm::errorCodeToError(std::make_error_code(std::errc::io_error));
}
private:
// Dispatches incoming message to Handler onNotify/onCall/onReply.
- bool handleMessage(json::Value Message, MessageHandler &Handler);
+ bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
// Writes outgoing message to Out stream.
- void sendMessage(json::Value Message) {
+ void sendMessage(llvm::json::Value Message) {
std::string S;
- raw_string_ostream OS(S);
- OS << formatv(Pretty ? "{0:2}" : "{0}", Message);
+ llvm::raw_string_ostream OS(S);
+ OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
OS.flush();
Out << "Content-Length: " << S.size() << "\r\n\r\n" << S;
Out.flush();
@@ -112,30 +115,31 @@ private:
}
// Read raw string messages from input stream.
- Optional<std::string> readRawMessage() {
+ llvm::Optional<std::string> readRawMessage() {
return Style == JSONStreamStyle::Delimited ? readDelimitedMessage()
: readStandardMessage();
}
- Optional<std::string> readDelimitedMessage();
- Optional<std::string> readStandardMessage();
+ llvm::Optional<std::string> readDelimitedMessage();
+ llvm::Optional<std::string> readStandardMessage();
std::FILE *In;
- raw_ostream &Out;
- raw_ostream &InMirror;
+ llvm::raw_ostream &Out;
+ llvm::raw_ostream &InMirror;
bool Pretty;
JSONStreamStyle Style;
};
-bool JSONTransport::handleMessage(json::Value Message,
+bool JSONTransport::handleMessage(llvm::json::Value Message,
MessageHandler &Handler) {
// Message must be an object with "jsonrpc":"2.0".
auto *Object = Message.getAsObject();
- if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0")) {
+ if (!Object ||
+ Object->getString("jsonrpc") != llvm::Optional<llvm::StringRef>("2.0")) {
elog("Not a JSON-RPC 2.0 message: {0:2}", Message);
return false;
}
// ID may be any JSON value. If absent, this is a notification.
- Optional<json::Value> ID;
+ llvm::Optional<llvm::json::Value> ID;
if (auto *I = Object->get("id"))
ID = std::move(*I);
auto Method = Object->getString("method");
@@ -147,13 +151,13 @@ bool JSONTransport::handleMessage(json::Value Message,
if (auto *Err = Object->getObject("error"))
return Handler.onReply(std::move(*ID), decodeError(*Err));
// Result should be given, use null if not.
- json::Value Result = nullptr;
+ llvm::json::Value Result = nullptr;
if (auto *R = Object->get("result"))
Result = std::move(*R);
return Handler.onReply(std::move(*ID), std::move(Result));
}
// Params should be given, use null if not.
- json::Value Params = nullptr;
+ llvm::json::Value Params = nullptr;
if (auto *P = Object->get("params"))
Params = std::move(*P);
@@ -172,7 +176,7 @@ bool readLine(std::FILE *In, std::string &Out) {
for (;;) {
Out.resize(Size + BufSize);
// Handle EINTR which is sent when a debugger attaches on some platforms.
- if (!sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
+ if (!llvm::sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
return false;
clearerr(In);
// If the line contained null bytes, anything after it (including \n) will
@@ -189,17 +193,17 @@ bool readLine(std::FILE *In, std::string &Out) {
// Returns None when:
// - ferror() or feof() are set.
// - Content-Length is missing or empty (protocol error)
-Optional<std::string> JSONTransport::readStandardMessage() {
+llvm::Optional<std::string> JSONTransport::readStandardMessage() {
// A Language Server Protocol message starts with a set of HTTP headers,
// delimited by \r\n, and terminated by an empty line (\r\n).
unsigned long long ContentLength = 0;
std::string Line;
while (true) {
if (feof(In) || ferror(In) || !readLine(In, Line))
- return None;
+ return llvm::None;
InMirror << Line;
- StringRef LineRef(Line);
+ llvm::StringRef LineRef(Line);
// We allow comments in headers. Technically this isn't part
@@ -214,7 +218,7 @@ Optional<std::string> JSONTransport::readStandardMessage() {
"The previous value for this message ({0}) was ignored.",
ContentLength);
}
- getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
+ llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
continue;
} else if (!LineRef.trim().empty()) {
// It's another header, ignore it.
@@ -231,24 +235,24 @@ Optional<std::string> JSONTransport::readStandardMessage() {
elog("Refusing to read message with long Content-Length: {0}. "
"Expect protocol errors",
ContentLength);
- return None;
+ return llvm::None;
}
if (ContentLength == 0) {
log("Warning: Missing Content-Length header, or zero-length message.");
- return None;
+ return llvm::None;
}
std::string JSON(ContentLength, '\0');
for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
// Handle EINTR which is sent when a debugger attaches on some platforms.
- Read = sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
- ContentLength - Pos, In);
+ Read = llvm::sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
+ ContentLength - Pos, In);
if (Read == 0) {
elog("Input was aborted. Read only {0} bytes of expected {1}.", Pos,
ContentLength);
- return None;
+ return llvm::None;
}
- InMirror << StringRef(&JSON[Pos], Read);
+ InMirror << llvm::StringRef(&JSON[Pos], Read);
clearerr(In); // If we're done, the error was transient. If we're not done,
// either it was transient or we'll see it again on retry.
Pos += Read;
@@ -261,12 +265,12 @@ Optional<std::string> JSONTransport::readStandardMessage() {
// - lines starting with # are ignored.
// This is a testing path, so favor simplicity over performance here.
// When returning None, feof() or ferror() will be set.
-Optional<std::string> JSONTransport::readDelimitedMessage() {
+llvm::Optional<std::string> JSONTransport::readDelimitedMessage() {
std::string JSON;
std::string Line;
while (readLine(In, Line)) {
InMirror << Line;
- auto LineRef = StringRef(Line).trim();
+ auto LineRef = llvm::StringRef(Line).trim();
if (LineRef.startswith("#")) // comment
continue;
@@ -279,15 +283,17 @@ Optional<std::string> JSONTransport::readDelimitedMessage() {
if (ferror(In)) {
elog("Input error while reading message!");
- return None;
+ return llvm::None;
}
return std::move(JSON); // Including at EOF
}
} // namespace
-std::unique_ptr<Transport> newJSONTransport(std::FILE *In, raw_ostream &Out,
- raw_ostream *InMirror, bool Pretty,
+std::unique_ptr<Transport> newJSONTransport(std::FILE *In,
+ llvm::raw_ostream &Out,
+ llvm::raw_ostream *InMirror,
+ bool Pretty,
JSONStreamStyle Style) {
return llvm::make_unique<JSONTransport>(In, Out, InMirror, Pretty, Style);
}
diff --git a/clang-tools-extra/clangd/Logger.cpp b/clang-tools-extra/clangd/Logger.cpp
index 6adf45dc9d1..9d4e7b93c72 100644
--- a/clang-tools-extra/clangd/Logger.cpp
+++ b/clang-tools-extra/clangd/Logger.cpp
@@ -14,7 +14,6 @@
#include "llvm/Support/raw_ostream.h"
#include <mutex>
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -29,13 +28,14 @@ LoggingSession::LoggingSession(clangd::Logger &Instance) {
LoggingSession::~LoggingSession() { L = nullptr; }
-void detail::log(Logger::Level Level, const formatv_object_base &Message) {
+void detail::log(Logger::Level Level,
+ const llvm::formatv_object_base &Message) {
if (L)
L->log(Level, Message);
else {
static std::mutex Mu;
std::lock_guard<std::mutex> Guard(Mu);
- errs() << Message << "\n";
+ llvm::errs() << Message << "\n";
}
}
@@ -48,14 +48,14 @@ const char *detail::debugType(const char *Filename) {
}
void StreamLogger::log(Logger::Level Level,
- const formatv_object_base &Message) {
+ const llvm::formatv_object_base &Message) {
if (Level < MinLevel)
return;
- sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
+ llvm::sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
trace::log(Message);
std::lock_guard<std::mutex> Guard(StreamMutex);
- Logs << formatv("{0}[{1:%H:%M:%S.%L}] {2}\n", indicator(Level), Timestamp,
- Message);
+ Logs << llvm::formatv("{0}[{1:%H:%M:%S.%L}] {2}\n", indicator(Level),
+ Timestamp, Message);
Logs.flush();
}
diff --git a/clang-tools-extra/clangd/Protocol.cpp b/clang-tools-extra/clangd/Protocol.cpp
index fd94ca7d4bc..cf3c6fd367a 100644
--- a/clang-tools-extra/clangd/Protocol.cpp
+++ b/clang-tools-extra/clangd/Protocol.cpp
@@ -24,14 +24,14 @@
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
-using namespace llvm;
namespace clang {
namespace clangd {
char LSPError::ID;
-URIForFile URIForFile::canonicalize(StringRef AbsPath, StringRef TUPath) {
- assert(sys::path::is_absolute(AbsPath) && "the path is relative");
+URIForFile URIForFile::canonicalize(llvm::StringRef AbsPath,
+ llvm::StringRef TUPath) {
+ assert(llvm::sys::path::is_absolute(AbsPath) && "the path is relative");
auto Resolved = URI::resolvePath(AbsPath, TUPath);
if (!Resolved) {
elog("URIForFile: failed to resolve path {0} with TU path {1}: "
@@ -42,14 +42,15 @@ URIForFile URIForFile::canonicalize(StringRef AbsPath, StringRef TUPath) {
return URIForFile(std::move(*Resolved));
}
-Expected<URIForFile> URIForFile::fromURI(const URI &U, StringRef HintPath) {
+llvm::Expected<URIForFile> URIForFile::fromURI(const URI &U,
+ llvm::StringRef HintPath) {
auto Resolved = URI::resolve(U, HintPath);
if (!Resolved)
return Resolved.takeError();
return URIForFile(std::move(*Resolved));
}
-bool fromJSON(const json::Value &E, URIForFile &R) {
+bool fromJSON(const llvm::json::Value &E, URIForFile &R) {
if (auto S = E.getAsString()) {
auto Parsed = URI::parse(*S);
if (!Parsed) {
@@ -73,89 +74,89 @@ bool fromJSON(const json::Value &E, URIForFile &R) {
return false;
}
-json::Value toJSON(const URIForFile &U) { return U.uri(); }
+llvm::json::Value toJSON(const URIForFile &U) { return U.uri(); }
-raw_ostream &operator<<(raw_ostream &OS, const URIForFile &U) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const URIForFile &U) {
return OS << U.uri();
}
-json::Value toJSON(const TextDocumentIdentifier &R) {
- return json::Object{{"uri", R.uri}};
+llvm::json::Value toJSON(const TextDocumentIdentifier &R) {
+ return llvm::json::Object{{"uri", R.uri}};
}
-bool fromJSON(const json::Value &Params, TextDocumentIdentifier &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, TextDocumentIdentifier &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("uri", R.uri);
}
-bool fromJSON(const json::Value &Params, Position &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, Position &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("line", R.line) && O.map("character", R.character);
}
-json::Value toJSON(const Position &P) {
- return json::Object{
+llvm::json::Value toJSON(const Position &P) {
+ return llvm::json::Object{
{"line", P.line},
{"character", P.character},
};
}
-raw_ostream &operator<<(raw_ostream &OS, const Position &P) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Position &P) {
return OS << P.line << ':' << P.character;
}
-bool fromJSON(const json::Value &Params, Range &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, Range &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("start", R.start) && O.map("end", R.end);
}
-json::Value toJSON(const Range &P) {
- return json::Object{
+llvm::json::Value toJSON(const Range &P) {
+ return llvm::json::Object{
{"start", P.start},
{"end", P.end},
};
}
-raw_ostream &operator<<(raw_ostream &OS, const Range &R) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Range &R) {
return OS << R.start << '-' << R.end;
}
-json::Value toJSON(const Location &P) {
- return json::Object{
+llvm::json::Value toJSON(const Location &P) {
+ return llvm::json::Object{
{"uri", P.uri},
{"range", P.range},
};
}
-raw_ostream &operator<<(raw_ostream &OS, const Location &L) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Location &L) {
return OS << L.range << '@' << L.uri;
}
-bool fromJSON(const json::Value &Params, TextDocumentItem &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, TextDocumentItem &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("uri", R.uri) && O.map("languageId", R.languageId) &&
O.map("version", R.version) && O.map("text", R.text);
}
-bool fromJSON(const json::Value &Params, TextEdit &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, TextEdit &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("range", R.range) && O.map("newText", R.newText);
}
-json::Value toJSON(const TextEdit &P) {
- return json::Object{
+llvm::json::Value toJSON(const TextEdit &P) {
+ return llvm::json::Object{
{"range", P.range},
{"newText", P.newText},
};
}
-raw_ostream &operator<<(raw_ostream &OS, const TextEdit &TE) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const TextEdit &TE) {
OS << TE.range << " => \"";
- printEscapedString(TE.newText, OS);
+ llvm::printEscapedString(TE.newText, OS);
return OS << '"';
}
-bool fromJSON(const json::Value &E, TraceLevel &Out) {
+bool fromJSON(const llvm::json::Value &E, TraceLevel &Out) {
if (auto S = E.getAsString()) {
if (*S == "off") {
Out = TraceLevel::Off;
@@ -171,7 +172,7 @@ bool fromJSON(const json::Value &E, TraceLevel &Out) {
return false;
}
-bool fromJSON(const json::Value &E, SymbolKind &Out) {
+bool fromJSON(const llvm::json::Value &E, SymbolKind &Out) {
if (auto T = E.getAsInteger()) {
if (*T < static_cast<int>(SymbolKind::File) ||
*T > static_cast<int>(SymbolKind::TypeParameter))
@@ -182,7 +183,7 @@ bool fromJSON(const json::Value &E, SymbolKind &Out) {
return false;
}
-bool fromJSON(const json::Value &E, SymbolKindBitset &Out) {
+bool fromJSON(const llvm::json::Value &E, SymbolKindBitset &Out) {
if (auto *A = E.getAsArray()) {
for (size_t I = 0; I < A->size(); ++I) {
SymbolKind KindOut;
@@ -212,8 +213,8 @@ SymbolKind adjustKindToCapability(SymbolKind Kind,
}
}
-bool fromJSON(const json::Value &Params, ClientCapabilities &R) {
- const json::Object *O = Params.getAsObject();
+bool fromJSON(const llvm::json::Value &Params, ClientCapabilities &R) {
+ const llvm::json::Object *O = Params.getAsObject();
if (!O)
return false;
if (auto *TextDocument = O->getObject("textDocument")) {
@@ -260,8 +261,8 @@ bool fromJSON(const json::Value &Params, ClientCapabilities &R) {
return true;
}
-bool fromJSON(const json::Value &Params, InitializeParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, InitializeParams &R) {
+ llvm::json::ObjectMapper O(Params);
if (!O)
return false;
// We deliberately don't fail if we can't parse individual fields.
@@ -275,24 +276,24 @@ bool fromJSON(const json::Value &Params, InitializeParams &R) {
return true;
}
-bool fromJSON(const json::Value &Params, DidOpenTextDocumentParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DidOpenTextDocumentParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("textDocument", R.textDocument);
}
-bool fromJSON(const json::Value &Params, DidCloseTextDocumentParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DidCloseTextDocumentParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("textDocument", R.textDocument);
}
-bool fromJSON(const json::Value &Params, DidChangeTextDocumentParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DidChangeTextDocumentParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("textDocument", R.textDocument) &&
O.map("contentChanges", R.contentChanges) &&
O.map("wantDiagnostics", R.wantDiagnostics);
}
-bool fromJSON(const json::Value &E, FileChangeType &Out) {
+bool fromJSON(const llvm::json::Value &E, FileChangeType &Out) {
if (auto T = E.getAsInteger()) {
if (*T < static_cast<int>(FileChangeType::Created) ||
*T > static_cast<int>(FileChangeType::Deleted))
@@ -303,61 +304,64 @@ bool fromJSON(const json::Value &E, FileChangeType &Out) {
return false;
}
-bool fromJSON(const json::Value &Params, FileEvent &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, FileEvent &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("uri", R.uri) && O.map("type", R.type);
}
-bool fromJSON(const json::Value &Params, DidChangeWatchedFilesParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DidChangeWatchedFilesParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("changes", R.changes);
}
-bool fromJSON(const json::Value &Params, TextDocumentContentChangeEvent &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params,
+ TextDocumentContentChangeEvent &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("range", R.range) && O.map("rangeLength", R.rangeLength) &&
O.map("text", R.text);
}
-bool fromJSON(const json::Value &Params, FormattingOptions &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, FormattingOptions &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("tabSize", R.tabSize) &&
O.map("insertSpaces", R.insertSpaces);
}
-json::Value toJSON(const FormattingOptions &P) {
- return json::Object{
+llvm::json::Value toJSON(const FormattingOptions &P) {
+ return llvm::json::Object{
{"tabSize", P.tabSize},
{"insertSpaces", P.insertSpaces},
};
}
-bool fromJSON(const json::Value &Params, DocumentRangeFormattingParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params,
+ DocumentRangeFormattingParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("textDocument", R.textDocument) &&
O.map("range", R.range) && O.map("options", R.options);
}
-bool fromJSON(const json::Value &Params, DocumentOnTypeFormattingParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params,
+ DocumentOnTypeFormattingParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("textDocument", R.textDocument) &&
O.map("position", R.position) && O.map("ch", R.ch) &&
O.map("options", R.options);
}
-bool fromJSON(const json::Value &Params, DocumentFormattingParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DocumentFormattingParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("textDocument", R.textDocument) &&
O.map("options", R.options);
}
-bool fromJSON(const json::Value &Params, DocumentSymbolParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DocumentSymbolParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("textDocument", R.textDocument);
}
-json::Value toJSON(const Diagnostic &D) {
- json::Object Diag{
+llvm::json::Value toJSON(const Diagnostic &D) {
+ llvm::json::Object Diag{
{"range", D.range},
{"severity", D.severity},
{"message", D.message},
@@ -369,8 +373,8 @@ json::Value toJSON(const Diagnostic &D) {
return std::move(Diag);
}
-bool fromJSON(const json::Value &Params, Diagnostic &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, Diagnostic &R) {
+ llvm::json::ObjectMapper O(Params);
if (!O || !O.map("range", R.range) || !O.map("message", R.message))
return false;
O.map("severity", R.severity);
@@ -378,12 +382,12 @@ bool fromJSON(const json::Value &Params, Diagnostic &R) {
return true;
}
-bool fromJSON(const json::Value &Params, CodeActionContext &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, CodeActionContext &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("diagnostics", R.diagnostics);
}
-raw_ostream &operator<<(raw_ostream &OS, const Diagnostic &D) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diagnostic &D) {
OS << D.range << " [";
switch (D.severity) {
case 1:
@@ -405,21 +409,21 @@ raw_ostream &operator<<(raw_ostream &OS, const Diagnostic &D) {
return OS << '(' << D.severity << "): " << D.message << "]";
}
-bool fromJSON(const json::Value &Params, CodeActionParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, CodeActionParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("textDocument", R.textDocument) &&
O.map("range", R.range) && O.map("context", R.context);
}
-bool fromJSON(const json::Value &Params, WorkspaceEdit &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, WorkspaceEdit &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("changes", R.changes);
}
-const StringLiteral ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND =
+const llvm::StringLiteral ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND =
"clangd.applyFix";
-bool fromJSON(const json::Value &Params, ExecuteCommandParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, ExecuteCommandParams &R) {
+ llvm::json::ObjectMapper O(Params);
if (!O || !O.map("command", R.command))
return false;
@@ -431,8 +435,8 @@ bool fromJSON(const json::Value &Params, ExecuteCommandParams &R) {
return false; // Unrecognized command.
}
-json::Value toJSON(const SymbolInformation &P) {
- return json::Object{
+llvm::json::Value toJSON(const SymbolInformation &P) {
+ return llvm::json::Object{
{"name", P.name},
{"kind", static_cast<int>(P.kind)},
{"location", P.location},
@@ -440,7 +444,8 @@ json::Value toJSON(const SymbolInformation &P) {
};
}
-raw_ostream &operator<<(raw_ostream &O, const SymbolInformation &SI) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
+ const SymbolInformation &SI) {
O << SI.containerName << "::" << SI.name << " - " << toJSON(SI);
return O;
}
@@ -451,10 +456,10 @@ bool operator==(const SymbolDetails &LHS, const SymbolDetails &RHS) {
}
llvm::json::Value toJSON(const SymbolDetails &P) {
- json::Object result{{"name", llvm::json::Value(nullptr)},
- {"containerName", llvm::json::Value(nullptr)},
- {"usr", llvm::json::Value(nullptr)},
- {"id", llvm::json::Value(nullptr)}};
+ llvm::json::Object result{{"name", llvm::json::Value(nullptr)},
+ {"containerName", llvm::json::Value(nullptr)},
+ {"usr", llvm::json::Value(nullptr)},
+ {"id", llvm::json::Value(nullptr)}};
if (!P.name.empty())
result["name"] = P.name;
@@ -469,13 +474,13 @@ llvm::json::Value toJSON(const SymbolDetails &P) {
result["id"] = P.ID.getValue().str();
// Older clang cannot compile 'return Result', even though it is legal.
- return json::Value(std::move(result));
+ return llvm::json::Value(std::move(result));
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const SymbolDetails &S) {
if (!S.containerName.empty()) {
O << S.containerName;
- StringRef ContNameRef;
+ llvm::StringRef ContNameRef;
if (!ContNameRef.endswith("::")) {
O << " ";
}
@@ -484,26 +489,26 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const SymbolDetails &S) {
return O;
}
-bool fromJSON(const json::Value &Params, WorkspaceSymbolParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, WorkspaceSymbolParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("query", R.query);
}
-json::Value toJSON(const Command &C) {
- auto Cmd = json::Object{{"title", C.title}, {"command", C.command}};
+llvm::json::Value toJSON(const Command &C) {
+ auto Cmd = llvm::json::Object{{"title", C.title}, {"command", C.command}};
if (C.workspaceEdit)
Cmd["arguments"] = {*C.workspaceEdit};
return std::move(Cmd);
}
-const StringLiteral CodeAction::QUICKFIX_KIND = "quickfix";
+const llvm::StringLiteral CodeAction::QUICKFIX_KIND = "quickfix";
-json::Value toJSON(const CodeAction &CA) {
- auto CodeAction = json::Object{{"title", CA.title}};
+llvm::json::Value toJSON(const CodeAction &CA) {
+ auto CodeAction = llvm::json::Object{{"title", CA.title}};
if (CA.kind)
CodeAction["kind"] = *CA.kind;
if (CA.diagnostics)
- CodeAction["diagnostics"] = json::Array(*CA.diagnostics);
+ CodeAction["diagnostics"] = llvm::json::Array(*CA.diagnostics);
if (CA.edit)
CodeAction["edit"] = *CA.edit;
if (CA.command)
@@ -511,15 +516,15 @@ json::Value toJSON(const CodeAction &CA) {
return std::move(CodeAction);
}
-raw_ostream &operator<<(raw_ostream &O, const DocumentSymbol &S) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const DocumentSymbol &S) {
return O << S.name << " - " << toJSON(S);
}
-json::Value toJSON(const DocumentSymbol &S) {
- json::Object Result{{"name", S.name},
- {"kind", static_cast<int>(S.kind)},
- {"range", S.range},
- {"selectionRange", S.selectionRange}};
+llvm::json::Value toJSON(const DocumentSymbol &S) {
+ llvm::json::Object Result{{"name", S.name},
+ {"kind", static_cast<int>(S.kind)},
+ {"range", S.range},
+ {"selectionRange", S.selectionRange}};
if (!S.detail.empty())
Result["detail"] = S.detail;
@@ -528,30 +533,30 @@ json::Value toJSON(const DocumentSymbol &S) {
if (S.deprecated)
Result["deprecated"] = true;
// Older gcc cannot compile 'return Result', even though it is legal.
- return json::Value(std::move(Result));
+ return llvm::json::Value(std::move(Result));
}
-json::Value toJSON(const WorkspaceEdit &WE) {
+llvm::json::Value toJSON(const WorkspaceEdit &WE) {
if (!WE.changes)
- return json::Object{};
- json::Object FileChanges;
+ return llvm::json::Object{};
+ llvm::json::Object FileChanges;
for (auto &Change : *WE.changes)
- FileChanges[Change.first] = json::Array(Change.second);
- return json::Object{{"changes", std::move(FileChanges)}};
+ FileChanges[Change.first] = llvm::json::Array(Change.second);
+ return llvm::json::Object{{"changes", std::move(FileChanges)}};
}
-json::Value toJSON(const ApplyWorkspaceEditParams &Params) {
- return json::Object{{"edit", Params.edit}};
+llvm::json::Value toJSON(const ApplyWorkspaceEditParams &Params) {
+ return llvm::json::Object{{"edit", Params.edit}};
}
-bool fromJSON(const json::Value &Params, TextDocumentPositionParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, TextDocumentPositionParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("textDocument", R.textDocument) &&
O.map("position", R.position);
}
bool fromJSON(const llvm::json::Value &Params, CompletionContext &R) {
- json::ObjectMapper O(Params);
+ llvm::json::ObjectMapper O(Params);
if (!O)
return false;
@@ -573,7 +578,7 @@ bool fromJSON(const llvm::json::Value &Params, CompletionParams &R) {
return true;
}
-static StringRef toTextKind(MarkupKind Kind) {
+static llvm::StringRef toTextKind(MarkupKind Kind) {
switch (Kind) {
case MarkupKind::PlainText:
return "plaintext";
@@ -583,18 +588,18 @@ static StringRef toTextKind(MarkupKind Kind) {
llvm_unreachable("Invalid MarkupKind");
}
-json::Value toJSON(const MarkupContent &MC) {
+llvm::json::Value toJSON(const MarkupContent &MC) {
if (MC.value.empty())
return nullptr;
- return json::Object{
+ return llvm::json::Object{
{"kind", toTextKind(MC.kind)},
{"value", MC.value},
};
}
-json::Value toJSON(const Hover &H) {
- json::Object Result{{"contents", toJSON(H.contents)}};
+llvm::json::Value toJSON(const Hover &H) {
+ llvm::json::Object Result{{"contents", toJSON(H.contents)}};
if (H.range.hasValue())
Result["range"] = toJSON(*H.range);
@@ -602,7 +607,7 @@ json::Value toJSON(const Hover &H) {
return std::move(Result);
}
-bool fromJSON(const json::Value &E, CompletionItemKind &Out) {
+bool fromJSON(const llvm::json::Value &E, CompletionItemKind &Out) {
if (auto T = E.getAsInteger()) {
if (*T < static_cast<int>(CompletionItemKind::Text) ||
*T > static_cast<int>(CompletionItemKind::TypeParameter))
@@ -635,7 +640,7 @@ adjustKindToCapability(CompletionItemKind Kind,
}
}
-bool fromJSON(const json::Value &E, CompletionItemKindBitset &Out) {
+bool fromJSON(const llvm::json::Value &E, CompletionItemKindBitset &Out) {
if (auto *A = E.getAsArray()) {
for (size_t I = 0; I < A->size(); ++I) {
CompletionItemKind KindOut;
@@ -647,9 +652,9 @@ bool fromJSON(const json::Value &E, CompletionItemKindBitset &Out) {
return false;
}
-json::Value toJSON(const CompletionItem &CI) {
+llvm::json::Value toJSON(const CompletionItem &CI) {
assert(!CI.label.empty() && "completion item label is required");
- json::Object Result{{"label", CI.label}};
+ llvm::json::Object Result{{"label", CI.label}};
if (CI.kind != CompletionItemKind::Missing)
Result["kind"] = static_cast<int>(CI.kind);
if (!CI.detail.empty())
@@ -667,13 +672,13 @@ json::Value toJSON(const CompletionItem &CI) {
if (CI.textEdit)
Result["textEdit"] = *CI.textEdit;
if (!CI.additionalTextEdits.empty())
- Result["additionalTextEdits"] = json::Array(CI.additionalTextEdits);
+ Result["additionalTextEdits"] = llvm::json::Array(CI.additionalTextEdits);
if (CI.deprecated)
Result["deprecated"] = CI.deprecated;
return std::move(Result);
}
-raw_ostream &operator<<(raw_ostream &O, const CompletionItem &I) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const CompletionItem &I) {
O << I.label << " - " << toJSON(I);
return O;
}
@@ -683,70 +688,72 @@ bool operator<(const CompletionItem &L, const CompletionItem &R) {
(R.sortText.empty() ? R.label : R.sortText);
}
-json::Value toJSON(const CompletionList &L) {
- return json::Object{
+llvm::json::Value toJSON(const CompletionList &L) {
+ return llvm::json::Object{
{"isIncomplete", L.isIncomplete},
- {"items", json::Array(L.items)},
+ {"items", llvm::json::Array(L.items)},
};
}
-json::Value toJSON(const ParameterInformation &PI) {
+llvm::json::Value toJSON(const ParameterInformation &PI) {
assert(!PI.label.empty() && "parameter information label is required");
- json::Object Result{{"label", PI.label}};
+ llvm::json::Object Result{{"label", PI.label}};
if (!PI.documentation.empty())
Result["documentation"] = PI.documentation;
return std::move(Result);
}
-json::Value toJSON(const SignatureInformation &SI) {
+llvm::json::Value toJSON(const SignatureInformation &SI) {
assert(!SI.label.empty() && "signature information label is required");
- json::Object Result{
+ llvm::json::Object Result{
{"label", SI.label},
- {"parameters", json::Array(SI.parameters)},
+ {"parameters", llvm::json::Array(SI.parameters)},
};
if (!SI.documentation.empty())
Result["documentation"] = SI.documentation;
return std::move(Result);
}
-raw_ostream &operator<<(raw_ostream &O, const SignatureInformation &I) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
+ const SignatureInformation &I) {
O << I.label << " - " << toJSON(I);
return O;
}
-json::Value toJSON(const SignatureHelp &SH) {
+llvm::json::Value toJSON(const SignatureHelp &SH) {
assert(SH.activeSignature >= 0 &&
"Unexpected negative value for number of active signatures.");
assert(SH.activeParameter >= 0 &&
"Unexpected negative value for active parameter index");
- return json::Object{
+ return llvm::json::Object{
{"activeSignature", SH.activeSignature},
{"activeParameter", SH.activeParameter},
- {"signatures", json::Array(SH.signatures)},
+ {"signatures", llvm::json::Array(SH.signatures)},
};
}
-bool fromJSON(const json::Value &Params, RenameParams &R) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, RenameParams &R) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("textDocument", R.textDocument) &&
O.map("position", R.position) && O.map("newName", R.newName);
}
-json::Value toJSON(const DocumentHighlight &DH) {
- return json::Object{
+llvm::json::Value toJSON(const DocumentHighlight &DH) {
+ return llvm::json::Object{
{"range", toJSON(DH.range)},
{"kind", static_cast<int>(DH.kind)},
};
}
llvm::json::Value toJSON(const FileStatus &FStatus) {
- return json::Object{
+ return llvm::json::Object{
{"uri", FStatus.uri},
{"state", FStatus.state},
};
}
-raw_ostream &operator<<(raw_ostream &O, const DocumentHighlight &V) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
+ const DocumentHighlight &V) {
O << V.range;
if (V.kind == DocumentHighlightKind::Read)
O << "(r)";
@@ -755,27 +762,29 @@ raw_ostream &operator<<(raw_ostream &O, const DocumentHighlight &V) {
return O;
}
-bool fromJSON(const json::Value &Params, DidChangeConfigurationParams &CCP) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params,
+ DidChangeConfigurationParams &CCP) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("settings", CCP.settings);
}
-bool fromJSON(const json::Value &Params, ClangdCompileCommand &CDbUpdate) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params,
+ ClangdCompileCommand &CDbUpdate) {
+ llvm::json::ObjectMapper O(Params);
return O && O.map("workingDirectory", CDbUpdate.workingDirectory) &&
O.map("compilationCommand", CDbUpdate.compilationCommand);
}
-bool fromJSON(const json::Value &Params, ConfigurationSettings &S) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, ConfigurationSettings &S) {
+ llvm::json::ObjectMapper O(Params);
if (!O)
return true; // 'any' type in LSP.
O.map("compilationDatabaseChanges", S.compilationDatabaseChanges);
return true;
}
-bool fromJSON(const json::Value &Params, InitializationOptions &Opts) {
- json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, InitializationOptions &Opts) {
+ llvm::json::ObjectMapper O(Params);
if (!O)
return true; // 'any' type in LSP.
@@ -786,7 +795,7 @@ bool fromJSON(const json::Value &Params, InitializationOptions &Opts) {
return true;
}
-bool fromJSON(const json::Value &Params, ReferenceParams &R) {
+bool fromJSON(const llvm::json::Value &Params, ReferenceParams &R) {
TextDocumentPositionParams &Base = R;
return fromJSON(Params, Base);
}
diff --git a/clang-tools-extra/clangd/Quality.cpp b/clang-tools-extra/clangd/Quality.cpp
index fe7a969eb3a..cef35c4ca0c 100644
--- a/clang-tools-extra/clangd/Quality.cpp
+++ b/clang-tools-extra/clangd/Quality.cpp
@@ -31,10 +31,9 @@
#include <algorithm>
#include <cmath>
-using namespace llvm;
namespace clang {
namespace clangd {
-static bool isReserved(StringRef Name) {
+static bool isReserved(llvm::StringRef Name) {
// FIXME: Should we exclude _Bool and others recognized by the standard?
return Name.size() >= 2 && Name[0] == '_' &&
(isUppercase(Name[1]) || Name[1] == '_');
@@ -249,12 +248,13 @@ float SymbolQualitySignals::evaluate() const {
return Score;
}
-raw_ostream &operator<<(raw_ostream &OS, const SymbolQualitySignals &S) {
- OS << formatv("=== Symbol quality: {0}\n", S.evaluate());
- OS << formatv("\tReferences: {0}\n", S.References);
- OS << formatv("\tDeprecated: {0}\n", S.Deprecated);
- OS << formatv("\tReserved name: {0}\n", S.ReservedName);
- OS << formatv("\tCategory: {0}\n", static_cast<int>(S.Category));
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+ const SymbolQualitySignals &S) {
+ OS << llvm::formatv("=== Symbol quality: {0}\n", S.evaluate());
+ OS << llvm::formatv("\tReferences: {0}\n", S.References);
+ OS << llvm::formatv("\tDeprecated: {0}\n", S.Deprecated);
+ OS << llvm::formatv("\tReserved name: {0}\n", S.ReservedName);
+ OS << llvm::formatv("\tCategory: {0}\n", static_cast<int>(S.Category));
return OS;
}
@@ -317,7 +317,7 @@ void SymbolRelevanceSignals::merge(const CodeCompletionResult &SemaCCResult) {
NeedsFixIts = !SemaCCResult.FixIts.empty();
}
-static std::pair<float, unsigned> uriProximity(StringRef SymbolURI,
+static std::pair<float, unsigned> uriProximity(llvm::StringRef SymbolURI,
URIDistance *D) {
if (!D || SymbolURI.empty())
return {0.f, 0u};
@@ -327,7 +327,7 @@ static std::pair<float, unsigned> uriProximity(StringRef SymbolURI,
}
static float scopeBoost(ScopeDistance &Distance,
- Optional<StringRef> SymbolScope) {
+ llvm::Optional<llvm::StringRef> SymbolScope) {
if (!SymbolScope)
return 1;
auto D = Distance.distance(*SymbolScope);
@@ -397,33 +397,34 @@ float SymbolRelevanceSignals::evaluate() const {
return Score;
}
-raw_ostream &operator<<(raw_ostream &OS, const SymbolRelevanceSignals &S) {
- OS << formatv("=== Symbol relevance: {0}\n", S.evaluate());
- OS << formatv("\tName match: {0}\n", S.NameMatch);
- OS << formatv("\tForbidden: {0}\n", S.Forbidden);
- OS << formatv("\tNeedsFixIts: {0}\n", S.NeedsFixIts);
- OS << formatv("\tIsInstanceMember: {0}\n", S.IsInstanceMember);
- OS << formatv("\tContext: {0}\n", getCompletionKindString(S.Context));
- OS << formatv("\tQuery type: {0}\n", static_cast<int>(S.Query));
- OS << formatv("\tScope: {0}\n", static_cast<int>(S.Scope));
-
- OS << formatv("\tSymbol URI: {0}\n", S.SymbolURI);
- OS << formatv("\tSymbol scope: {0}\n",
- S.SymbolScope ? *S.SymbolScope : "<None>");
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+ const SymbolRelevanceSignals &S) {
+ OS << llvm::formatv("=== Symbol relevance: {0}\n", S.evaluate());
+ OS << llvm::formatv("\tName match: {0}\n", S.NameMatch);
+ OS << llvm::formatv("\tForbidden: {0}\n", S.Forbidden);
+ OS << llvm::formatv("\tNeedsFixIts: {0}\n", S.NeedsFixIts);
+ OS << llvm::formatv("\tIsInstanceMember: {0}\n", S.IsInstanceMember);
+ OS << llvm::formatv("\tContext: {0}\n", getCompletionKindString(S.Context));
+ OS << llvm::formatv("\tQuery type: {0}\n", static_cast<int>(S.Query));
+ OS << llvm::formatv("\tScope: {0}\n", static_cast<int>(S.Scope));
+
+ OS << llvm::formatv("\tSymbol URI: {0}\n", S.SymbolURI);
+ OS << llvm::formatv("\tSymbol scope: {0}\n",
+ S.SymbolScope ? *S.SymbolScope : "<None>");
if (S.FileProximityMatch) {
auto Score = uriProximity(S.SymbolURI, S.FileProximityMatch);
- OS << formatv("\tIndex URI proximity: {0} (distance={1})\n", Score.first,
- Score.second);
+ OS << llvm::formatv("\tIndex URI proximity: {0} (distance={1})\n",
+ Score.first, Score.second);
}
- OS << formatv("\tSema file proximity: {0}\n", S.SemaFileProximityScore);
+ OS << llvm::formatv("\tSema file proximity: {0}\n", S.SemaFileProximityScore);
- OS << formatv("\tSema says in scope: {0}\n", S.SemaSaysInScope);
+ OS << llvm::formatv("\tSema says in scope: {0}\n", S.SemaSaysInScope);
if (S.ScopeProximityMatch)
- OS << formatv("\tIndex scope boost: {0}\n",
- scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));
+ OS << llvm::formatv("\tIndex scope boost: {0}\n",
+ scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));
- OS << formatv(
+ OS << llvm::formatv(
"\tType matched preferred: {0} (Context type: {1}, Symbol type: {2}\n",
S.TypeMatchesPreferred, S.HadContextType, S.HadSymbolType);
@@ -441,33 +442,34 @@ static uint32_t encodeFloat(float F) {
constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);
// Get the bits of the float. Endianness is the same as for integers.
- uint32_t U = FloatToBits(F);
+ uint32_t U = llvm::FloatToBits(F);
// IEEE 754 floats compare like sign-magnitude integers.
if (U & TopBit) // Negative float.
return 0 - U; // Map onto the low half of integers, order reversed.
return U + TopBit; // Positive floats map onto the high half of integers.
}
-std::string sortText(float Score, StringRef Name) {
+std::string sortText(float Score, llvm::StringRef Name) {
// We convert -Score to an integer, and hex-encode for readability.
// Example: [0.5, "foo"] -> "41000000foo"
std::string S;
- raw_string_ostream OS(S);
- write_hex(OS, encodeFloat(-Score), HexPrintStyle::Lower,
- /*Width=*/2 * sizeof(Score));
+ llvm::raw_string_ostream OS(S);
+ llvm::write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower,
+ /*Width=*/2 * sizeof(Score));
OS << Name;
OS.flush();
return S;
}
-raw_ostream &operator<<(raw_ostream &OS, const SignatureQualitySignals &S) {
- OS << formatv("=== Signature Quality:\n");
- OS << formatv("\tNumber of parameters: {0}\n", S.NumberOfParameters);
- OS << formatv("\tNumber of optional parameters: {0}\n",
- S.NumberOfOptionalParameters);
- OS << formatv("\tContains active parameter: {0}\n",
- S.ContainsActiveParameter);
- OS << formatv("\tKind: {0}\n", S.Kind);
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+ const SignatureQualitySignals &S) {
+ OS << llvm::formatv("=== Signature Quality:\n");
+ OS << llvm::formatv("\tNumber of parameters: {0}\n", S.NumberOfParameters);
+ OS << llvm::formatv("\tNumber of optional parameters: {0}\n",
+ S.NumberOfOptionalParameters);
+ OS << llvm::formatv("\tContains active parameter: {0}\n",
+ S.ContainsActiveParameter);
+ OS << llvm::formatv("\tKind: {0}\n", S.Kind);
return OS;
}
diff --git a/clang-tools-extra/clangd/RIFF.cpp b/clang-tools-extra/clangd/RIFF.cpp
index 19722b620d4..c0bf7855fcb 100644
--- a/clang-tools-extra/clangd/RIFF.cpp
+++ b/clang-tools-extra/clangd/RIFF.cpp
@@ -10,22 +10,21 @@
#include "RIFF.h"
#include "llvm/Support/Endian.h"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace riff {
-static Error makeError(const char *Msg) {
- return createStringError(inconvertibleErrorCode(), Msg);
+static llvm::Error makeError(const char *Msg) {
+ return llvm::createStringError(llvm::inconvertibleErrorCode(), Msg);
}
-Expected<Chunk> readChunk(StringRef &Stream) {
+llvm::Expected<Chunk> readChunk(llvm::StringRef &Stream) {
if (Stream.size() < 8)
return makeError("incomplete chunk header");
Chunk C;
std::copy(Stream.begin(), Stream.begin() + 4, C.ID.begin());
Stream = Stream.drop_front(4);
- uint32_t Len = support::endian::read32le(Stream.take_front(4).begin());
+ uint32_t Len = llvm::support::endian::read32le(Stream.take_front(4).begin());
Stream = Stream.drop_front(4);
if (Stream.size() < Len)
return makeError("truncated chunk");
@@ -39,10 +38,10 @@ Expected<Chunk> readChunk(StringRef &Stream) {
return std::move(C);
}
-raw_ostream &operator<<(raw_ostream &OS, const Chunk &C) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Chunk &C) {
OS.write(C.ID.data(), C.ID.size());
char Size[4];
- support::endian::write32le(Size, C.Data.size());
+ llvm::support::endian::write32le(Size, C.Data.size());
OS.write(Size, sizeof(Size));
OS << C.Data;
if (C.Data.size() % 2)
@@ -50,7 +49,7 @@ raw_ostream &operator<<(raw_ostream &OS, const Chunk &C) {
return OS;
}
-Expected<File> readFile(StringRef Stream) {
+llvm::Expected<File> readFile(llvm::StringRef Stream) {
auto RIFF = readChunk(Stream);
if (!RIFF)
return RIFF.takeError();
@@ -60,7 +59,7 @@ Expected<File> readFile(StringRef Stream) {
return makeError("RIFF chunk too short");
File F;
std::copy(RIFF->Data.begin(), RIFF->Data.begin() + 4, F.Type.begin());
- for (StringRef Body = RIFF->Data.drop_front(4); !Body.empty();)
+ for (llvm::StringRef Body = RIFF->Data.drop_front(4); !Body.empty();)
if (auto Chunk = readChunk(Body)) {
F.Chunks.push_back(*Chunk);
} else
@@ -68,14 +67,14 @@ Expected<File> readFile(StringRef Stream) {
return std::move(F);
}
-raw_ostream &operator<<(raw_ostream &OS, const File &F) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const File &F) {
// To avoid copies, we serialize the outer RIFF chunk "by hand".
size_t DataLen = 4; // Predict length of RIFF chunk data.
for (const auto &C : F.Chunks)
DataLen += 4 + 4 + C.Data.size() + (C.Data.size() % 2);
OS << "RIFF";
char Size[4];
- support::endian::write32le(Size, DataLen);
+ llvm::support::endian::write32le(Size, DataLen);
OS.write(Size, sizeof(Size));
OS.write(F.Type.data(), F.Type.size());
for (const auto &C : F.Chunks)
diff --git a/clang-tools-extra/clangd/SourceCode.cpp b/clang-tools-extra/clangd/SourceCode.cpp
index ce22676dc23..343fc70113f 100644
--- a/clang-tools-extra/clangd/SourceCode.cpp
+++ b/clang-tools-extra/clangd/SourceCode.cpp
@@ -16,7 +16,6 @@
#include "llvm/Support/Error.h"
#include "llvm/Support/Path.h"
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -27,7 +26,7 @@ namespace clangd {
// invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true.
// Returns true if CB returned true, false if we hit the end of string.
template <typename Callback>
-static bool iterateCodepoints(StringRef U8, const Callback &CB) {
+static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
for (size_t I = 0; I < U8.size();) {
unsigned char C = static_cast<unsigned char>(U8[I]);
if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
@@ -37,7 +36,7 @@ static bool iterateCodepoints(StringRef U8, const Callback &CB) {
continue;
}
// This convenient property of UTF-8 holds for all non-ASCII characters.
- size_t UTF8Length = countLeadingOnes(C);
+ size_t UTF8Length = llvm::countLeadingOnes(C);
// 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here.
// 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug.
assert((UTF8Length >= 2 && UTF8Length <= 4) &&
@@ -54,7 +53,7 @@ static bool iterateCodepoints(StringRef U8, const Callback &CB) {
// Returns the offset into the string that matches \p Units UTF-16 code units.
// Conceptually, this converts to UTF-16, truncates to CodeUnits, converts back
// to UTF-8, and returns the length in bytes.
-static size_t measureUTF16(StringRef U8, int U16Units, bool &Valid) {
+static size_t measureUTF16(llvm::StringRef U8, int U16Units, bool &Valid) {
size_t Result = 0;
Valid = U16Units == 0 || iterateCodepoints(U8, [&](int U8Len, int U16Len) {
Result += U8Len;
@@ -68,7 +67,7 @@ static size_t measureUTF16(StringRef U8, int U16Units, bool &Valid) {
}
// Like most strings in clangd, the input is UTF-8 encoded.
-size_t lspLength(StringRef Code) {
+size_t lspLength(llvm::StringRef Code) {
// A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
// Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx.
size_t Count = 0;
@@ -79,47 +78,47 @@ size_t lspLength(StringRef Code) {
return Count;
}
-Expected<size_t> positionToOffset(StringRef Code, Position P,
- bool AllowColumnsBeyondLineLength) {
+llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
+ bool AllowColumnsBeyondLineLength) {
if (P.line < 0)
- return make_error<StringError>(
- formatv("Line value can't be negative ({0})", P.line),
- errc::invalid_argument);
+ return llvm::make_error<llvm::StringError>(
+ llvm::formatv("Line value can't be negative ({0})", P.line),
+ llvm::errc::invalid_argument);
if (P.character < 0)
- return make_error<StringError>(
- formatv("Character value can't be negative ({0})", P.character),
- errc::invalid_argument);
+ return llvm::make_error<llvm::StringError>(
+ llvm::formatv("Character value can't be negative ({0})", P.character),
+ llvm::errc::invalid_argument);
size_t StartOfLine = 0;
for (int I = 0; I != P.line; ++I) {
size_t NextNL = Code.find('\n', StartOfLine);
- if (NextNL == StringRef::npos)
- return make_error<StringError>(
- formatv("Line value is out of range ({0})", P.line),
- errc::invalid_argument);
+ 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);
StartOfLine = NextNL + 1;
}
size_t NextNL = Code.find('\n', StartOfLine);
- if (NextNL == StringRef::npos)
+ if (NextNL == llvm::StringRef::npos)
NextNL = Code.size();
bool Valid;
size_t ByteOffsetInLine = measureUTF16(
Code.substr(StartOfLine, NextNL - StartOfLine), P.character, Valid);
if (!Valid && !AllowColumnsBeyondLineLength)
- return make_error<StringError>(
- formatv("UTF-16 offset {0} is invalid for line {1}", P.character,
- P.line),
- errc::invalid_argument);
+ return llvm::make_error<llvm::StringError>(
+ llvm::formatv("UTF-16 offset {0} is invalid for line {1}", P.character,
+ P.line),
+ llvm::errc::invalid_argument);
return StartOfLine + ByteOffsetInLine;
}
-Position offsetToPosition(StringRef Code, size_t Offset) {
+Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
Offset = std::min(Code.size(), Offset);
- StringRef Before = Code.substr(0, Offset);
+ llvm::StringRef Before = Code.substr(0, Offset);
int Lines = Before.count('\n');
size_t PrevNL = Before.rfind('\n');
- size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
+ size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Position Pos;
Pos.line = Lines;
Pos.character = lspLength(Before.substr(StartOfLine));
@@ -134,7 +133,7 @@ Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
Position P;
P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
bool Invalid = false;
- StringRef Code = SM.getBufferData(FID, &Invalid);
+ llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
if (!Invalid) {
auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
@@ -151,31 +150,33 @@ Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
return {Begin, End};
}
-std::pair<size_t, size_t> offsetToClangLineColumn(StringRef Code,
+std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
size_t Offset) {
Offset = std::min(Code.size(), Offset);
- StringRef Before = Code.substr(0, Offset);
+ llvm::StringRef Before = Code.substr(0, Offset);
int Lines = Before.count('\n');
size_t PrevNL = Before.rfind('\n');
- size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
+ size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
return {Lines + 1, Offset - StartOfLine + 1};
}
-std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
+std::pair<llvm::StringRef, llvm::StringRef>
+splitQualifiedName(llvm::StringRef QName) {
size_t Pos = QName.rfind("::");
- if (Pos == StringRef::npos)
- return {StringRef(), QName};
+ if (Pos == llvm::StringRef::npos)
+ return {llvm::StringRef(), QName};
return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
}
-TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R) {
+TextEdit replacementToEdit(llvm::StringRef Code,
+ const tooling::Replacement &R) {
Range ReplacementRange = {
offsetToPosition(Code, R.getOffset()),
offsetToPosition(Code, R.getOffset() + R.getLength())};
return {ReplacementRange, R.getReplacementText()};
}
-std::vector<TextEdit> replacementsToEdits(StringRef Code,
+std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
const tooling::Replacements &Repls) {
std::vector<TextEdit> Edits;
for (const auto &R : Repls)
@@ -183,13 +184,13 @@ std::vector<TextEdit> replacementsToEdits(StringRef Code,
return Edits;
}
-Optional<std::string> getCanonicalPath(const FileEntry *F,
- const SourceManager &SourceMgr) {
+llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
+ const SourceManager &SourceMgr) {
if (!F)
return None;
- SmallString<128> FilePath = F->getName();
- if (!sys::path::is_absolute(FilePath)) {
+ llvm::SmallString<128> FilePath = F->getName();
+ if (!llvm::sys::path::is_absolute(FilePath)) {
if (auto EC =
SourceMgr.getFileManager().getVirtualFileSystem()->makeAbsolute(
FilePath)) {
@@ -211,10 +212,11 @@ Optional<std::string> getCanonicalPath(const FileEntry *F,
// The file path of Symbol is "/project/src/foo.h" instead of
// "/tmp/build/foo.h"
if (const DirectoryEntry *Dir = SourceMgr.getFileManager().getDirectory(
- sys::path::parent_path(FilePath))) {
- SmallString<128> RealPath;
- StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
- sys::path::append(RealPath, DirName, sys::path::filename(FilePath));
+ llvm::sys::path::parent_path(FilePath))) {
+ llvm::SmallString<128> RealPath;
+ llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
+ llvm::sys::path::append(RealPath, DirName,
+ llvm::sys::path::filename(FilePath));
return RealPath.str().str();
}
@@ -235,13 +237,13 @@ bool IsRangeConsecutive(const Range &Left, const Range &Right) {
Left.end.character == Right.start.character;
}
-FileDigest digest(StringRef Content) {
+FileDigest digest(llvm::StringRef Content) {
return llvm::SHA1::hash({(const uint8_t *)Content.data(), Content.size()});
}
-Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
+llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
bool Invalid = false;
- StringRef Content = SM.getBufferData(FID, &Invalid);
+ llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
if (Invalid)
return None;
return digest(Content);
diff --git a/clang-tools-extra/clangd/TUScheduler.cpp b/clang-tools-extra/clangd/TUScheduler.cpp
index b7f79436104..23264004695 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -56,7 +56,6 @@
#include <queue>
#include <thread>
-using namespace llvm;
namespace clang {
namespace clangd {
using std::chrono::steady_clock;
@@ -67,9 +66,9 @@ class ASTWorker;
static clang::clangd::Key<std::string> kFileBeingProcessed;
-Optional<StringRef> TUScheduler::getFileBeingProcessedInContext() {
+llvm::Optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
if (auto *File = Context::current().get(kFileBeingProcessed))
- return StringRef(*File);
+ return llvm::StringRef(*File);
return None;
}
@@ -113,7 +112,7 @@ public:
/// Returns the cached value for \p K, or llvm::None if the value is not in
/// the cache anymore. If nullptr was cached for \p K, this function will
/// return a null unique_ptr wrapped into an optional.
- Optional<std::unique_ptr<ParsedAST>> take(Key K) {
+ llvm::Optional<std::unique_ptr<ParsedAST>> take(Key K) {
std::unique_lock<std::mutex> Lock(Mut);
auto Existing = findByKey(K);
if (Existing == LRU.end())
@@ -123,7 +122,7 @@ public:
// GCC 4.8 fails to compile `return V;`, as it tries to call the copy
// constructor of unique_ptr, so we call the move ctor explicitly to avoid
// this miscompile.
- return Optional<std::unique_ptr<ParsedAST>>(std::move(V));
+ return llvm::Optional<std::unique_ptr<ParsedAST>>(std::move(V));
}
private:
@@ -177,15 +176,16 @@ public:
~ASTWorker();
void update(ParseInputs Inputs, WantDiagnostics);
- void runWithAST(StringRef Name,
- unique_function<void(Expected<InputsAndAST>)> Action);
+ void
+ runWithAST(llvm::StringRef Name,
+ llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action);
bool blockUntilIdle(Deadline Timeout) const;
std::shared_ptr<const PreambleData> getPossiblyStalePreamble() const;
/// Obtain a preamble reflecting all updates so far. Threadsafe.
/// It may be delivered immediately, or later on the worker thread.
void getCurrentPreamble(
- unique_function<void(std::shared_ptr<const PreambleData>)>);
+ llvm::unique_function<void(std::shared_ptr<const PreambleData>)>);
/// Wait for the first build of preamble to finish. Preamble itself can be
/// accessed via getPossiblyStalePreamble(). Note that this function will
/// return after an unsuccessful build of the preamble too, i.e. result of
@@ -203,8 +203,8 @@ private:
/// Signal that run() should finish processing pending requests and exit.
void stop();
/// Adds a new task to the end of the request queue.
- void startTask(StringRef Name, unique_function<void()> Task,
- Optional<WantDiagnostics> UpdateType);
+ void startTask(llvm::StringRef Name, llvm::unique_function<void()> Task,
+ llvm::Optional<WantDiagnostics> UpdateType);
/// Updates the TUStatus and emits it. Only called in the worker thread.
void emitTUStatus(TUAction FAction,
const TUStatus::BuildDetails *Detail = nullptr);
@@ -218,11 +218,11 @@ private:
bool shouldSkipHeadLocked() const;
struct Request {
- unique_function<void()> Action;
+ llvm::unique_function<void()> Action;
std::string Name;
steady_clock::time_point AddTime;
Context Ctx;
- Optional<WantDiagnostics> UpdateType;
+ llvm::Optional<WantDiagnostics> UpdateType;
};
/// Handles retention of ASTs.
@@ -321,7 +321,7 @@ ASTWorkerHandle ASTWorker::create(PathRef FileName,
FileName, IdleASTs, Barrier, /*RunSync=*/!Tasks, UpdateDebounce,
std::move(PCHs), StorePreamblesInMemory, Callbacks));
if (Tasks)
- Tasks->runAsync("worker:" + sys::path::filename(FileName),
+ Tasks->runAsync("worker:" + llvm::sys::path::filename(FileName),
[Worker]() { Worker->run(); });
return ASTWorkerHandle(std::move(Worker));
@@ -350,7 +350,7 @@ ASTWorker::~ASTWorker() {
}
void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags) {
- StringRef TaskName = "Update";
+ llvm::StringRef TaskName = "Update";
auto Task = [=]() mutable {
// Will be used to check if we can avoid rebuilding the AST.
bool InputsAreTheSame =
@@ -364,7 +364,7 @@ void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags) {
emitTUStatus({TUAction::BuildingPreamble, TaskName});
log("Updating file {0} with command [{1}] {2}", FileName,
Inputs.CompileCommand.Directory,
- join(Inputs.CompileCommand.CommandLine, " "));
+ llvm::join(Inputs.CompileCommand.CommandLine, " "));
// Rebuild the preamble and the AST.
std::unique_ptr<CompilerInvocation> Invocation =
buildCompilerInvocation(Inputs);
@@ -437,9 +437,9 @@ void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags) {
}
// Get the AST for diagnostics.
- Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
+ llvm::Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
if (!AST) {
- Optional<ParsedAST> NewAST =
+ llvm::Optional<ParsedAST> NewAST =
buildAST(FileName, std::move(Invocation), Inputs, NewPreamble, PCHs);
AST = NewAST ? llvm::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
if (!(*AST)) { // buildAST fails.
@@ -474,16 +474,17 @@ void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags) {
}
void ASTWorker::runWithAST(
- StringRef Name, unique_function<void(Expected<InputsAndAST>)> Action) {
+ llvm::StringRef Name,
+ llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action) {
auto Task = [=](decltype(Action) Action) {
if (isCancelled())
- return Action(make_error<CancelledError>());
- Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
+ return Action(llvm::make_error<CancelledError>());
+ llvm::Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
if (!AST) {
std::unique_ptr<CompilerInvocation> Invocation =
buildCompilerInvocation(FileInputs);
// Try rebuilding the AST.
- Optional<ParsedAST> NewAST =
+ llvm::Optional<ParsedAST> NewAST =
Invocation
? buildAST(FileName,
llvm::make_unique<CompilerInvocation>(*Invocation),
@@ -492,12 +493,12 @@ void ASTWorker::runWithAST(
AST = NewAST ? llvm::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
}
// Make sure we put the AST back into the LRU cache.
- auto _ = make_scope_exit(
+ auto _ = llvm::make_scope_exit(
[&AST, this]() { IdleASTs.put(this, std::move(*AST)); });
// Run the user-provided action.
if (!*AST)
- return Action(
- make_error<StringError>("invalid AST", errc::invalid_argument));
+ return Action(llvm::make_error<llvm::StringError>(
+ "invalid AST", llvm::errc::invalid_argument));
Action(InputsAndAST{FileInputs, **AST});
};
startTask(Name, Bind(Task, std::move(Action)),
@@ -511,7 +512,7 @@ ASTWorker::getPossiblyStalePreamble() const {
}
void ASTWorker::getCurrentPreamble(
- unique_function<void(std::shared_ptr<const PreambleData>)> Callback) {
+ llvm::unique_function<void(std::shared_ptr<const PreambleData>)> Callback) {
// We could just call startTask() to throw the read on the queue, knowing
// it will run after any updates. But we know this task is cheap, so to
// improve latency we cheat: insert it on the queue after the last update.
@@ -565,11 +566,12 @@ void ASTWorker::stop() {
RequestsCV.notify_all();
}
-void ASTWorker::startTask(StringRef Name, unique_function<void()> Task,
- Optional<WantDiagnostics> UpdateType) {
+void ASTWorker::startTask(llvm::StringRef Name,
+ llvm::unique_function<void()> Task,
+ llvm::Optional<WantDiagnostics> UpdateType) {
if (RunSync) {
assert(!Done && "running a task after stop()");
- trace::Span Tracer(Name + ":" + sys::path::filename(FileName));
+ trace::Span Tracer(Name + ":" + llvm::sys::path::filename(FileName));
Task();
return;
}
@@ -611,8 +613,8 @@ void ASTWorker::run() {
}
// Tracing: we have a next request, attribute this sleep to it.
- Optional<WithContext> Ctx;
- Optional<trace::Span> Tracer;
+ llvm::Optional<WithContext> Ctx;
+ llvm::Optional<trace::Span> Tracer;
if (!Requests.empty()) {
Ctx.emplace(Requests.front().Ctx.clone());
Tracer.emplace("Debounce");
@@ -734,7 +736,7 @@ bool ASTWorker::blockUntilIdle(Deadline Timeout) const {
// are familiar by C++ programmers.
std::string renderTUAction(const TUAction &Action) {
std::string Result;
- raw_string_ostream OS(Result);
+ llvm::raw_string_ostream OS(Result);
switch (Action.S) {
case TUAction::Queued:
OS << "file is queued";
@@ -844,19 +846,20 @@ void TUScheduler::remove(PathRef File) {
File);
}
-void TUScheduler::run(StringRef Name, unique_function<void()> Action) {
+void TUScheduler::run(llvm::StringRef Name,
+ llvm::unique_function<void()> Action) {
if (!PreambleTasks)
return Action();
PreambleTasks->runAsync(Name, std::move(Action));
}
void TUScheduler::runWithAST(
- StringRef Name, PathRef File,
- unique_function<void(Expected<InputsAndAST>)> Action) {
+ llvm::StringRef Name, PathRef File,
+ llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action) {
auto It = Files.find(File);
if (It == Files.end()) {
- Action(make_error<LSPError>("trying to get AST for non-added document",
- ErrorCode::InvalidParams));
+ Action(llvm::make_error<LSPError>(
+ "trying to get AST for non-added document", ErrorCode::InvalidParams));
return;
}
@@ -864,12 +867,13 @@ void TUScheduler::runWithAST(
}
void TUScheduler::runWithPreamble(
- StringRef Name, PathRef File, PreambleConsistency Consistency,
- unique_function<void(Expected<InputsAndPreamble>)> Action) {
+ llvm::StringRef Name, PathRef File, PreambleConsistency Consistency,
+ llvm::unique_function<void(llvm::Expected<InputsAndPreamble>)> Action) {
auto It = Files.find(File);
if (It == Files.end()) {
- Action(make_error<LSPError>("trying to get preamble for non-added document",
- ErrorCode::InvalidParams));
+ Action(llvm::make_error<LSPError>(
+ "trying to get preamble for non-added document",
+ ErrorCode::InvalidParams));
return;
}
@@ -921,7 +925,7 @@ void TUScheduler::runWithPreamble(
};
PreambleTasks->runAsync(
- "task:" + sys::path::filename(File),
+ "task:" + llvm::sys::path::filename(File),
Bind(Task, std::string(Name), std::string(File), It->second->Contents,
It->second->Command,
Context::current().derive(kFileBeingProcessed, File),
diff --git a/clang-tools-extra/clangd/Threading.cpp b/clang-tools-extra/clangd/Threading.cpp
index abfe0f497ca..139fcc2f878 100644
--- a/clang-tools-extra/clangd/Threading.cpp
+++ b/clang-tools-extra/clangd/Threading.cpp
@@ -9,7 +9,6 @@
#include <pthread.h>
#endif
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -64,14 +63,14 @@ bool AsyncTaskRunner::wait(Deadline D) const {
[&] { return InFlightTasks == 0; });
}
-void AsyncTaskRunner::runAsync(const Twine &Name,
- unique_function<void()> Action) {
+void AsyncTaskRunner::runAsync(const llvm::Twine &Name,
+ llvm::unique_function<void()> Action) {
{
std::lock_guard<std::mutex> Lock(Mutex);
++InFlightTasks;
}
- auto CleanupTask = make_scope_exit([this]() {
+ auto CleanupTask = llvm::make_scope_exit([this]() {
std::lock_guard<std::mutex> Lock(Mutex);
int NewTasksCnt = --InFlightTasks;
if (NewTasksCnt == 0) {
@@ -83,7 +82,7 @@ void AsyncTaskRunner::runAsync(const Twine &Name,
std::thread(
[](std::string Name, decltype(Action) Action, decltype(CleanupTask)) {
- set_thread_name(Name);
+ llvm::set_thread_name(Name);
Action();
// Make sure function stored by Action is destroyed before CleanupTask
// is run.
@@ -93,7 +92,7 @@ void AsyncTaskRunner::runAsync(const Twine &Name,
.detach();
}
-Deadline timeoutSeconds(Optional<double> Seconds) {
+Deadline timeoutSeconds(llvm::Optional<double> Seconds) {
using namespace std::chrono;
if (!Seconds)
return Deadline::infinity();
diff --git a/clang-tools-extra/clangd/Trace.cpp b/clang-tools-extra/clangd/Trace.cpp
index 4d73dabcf04..e44d3a138b3 100644
--- a/clang-tools-extra/clangd/Trace.cpp
+++ b/clang-tools-extra/clangd/Trace.cpp
@@ -19,7 +19,6 @@
#include <atomic>
#include <mutex>
-using namespace llvm;
namespace clang {
namespace clangd {
namespace trace {
@@ -29,16 +28,16 @@ namespace {
// Perhaps we should replace this by something that disturbs performance less.
class JSONTracer : public EventTracer {
public:
- JSONTracer(raw_ostream &Out, bool Pretty)
+ JSONTracer(llvm::raw_ostream &Out, bool Pretty)
: Out(Out), Sep(""), Start(std::chrono::system_clock::now()),
JSONFormat(Pretty ? "{0:2}" : "{0}") {
// The displayTimeUnit must be ns to avoid low-precision overlap
// calculations!
Out << R"({"displayTimeUnit":"ns","traceEvents":[)"
<< "\n";
- rawEvent("M", json::Object{
+ rawEvent("M", llvm::json::Object{
{"name", "process_name"},
- {"args", json::Object{{"name", "clangd"}}},
+ {"args", llvm::json::Object{{"name", "clangd"}}},
});
}
@@ -49,7 +48,7 @@ public:
// We stash a Span object in the context. It will record the start/end,
// and this also allows us to look up the parent Span's information.
- Context beginSpan(StringRef Name, json::Object *Args) override {
+ Context beginSpan(llvm::StringRef Name, llvm::json::Object *Args) override {
return Context::current().derive(
SpanKey, llvm::make_unique<JSONSpan>(this, Name, Args));
}
@@ -62,15 +61,16 @@ public:
Context::current().getExisting(SpanKey)->markEnded();
}
- void instant(StringRef Name, json::Object &&Args) override {
+ void instant(llvm::StringRef Name, llvm::json::Object &&Args) override {
captureThreadMetadata();
- jsonEvent("i", json::Object{{"name", Name}, {"args", std::move(Args)}});
+ jsonEvent("i",
+ llvm::json::Object{{"name", Name}, {"args", std::move(Args)}});
}
// Record an event on the current thread. ph, pid, tid, ts are set.
// Contents must be a list of the other JSON key/values.
- void jsonEvent(StringRef Phase, json::Object &&Contents,
- uint64_t TID = get_threadid(), double Timestamp = 0) {
+ void jsonEvent(llvm::StringRef Phase, llvm::json::Object &&Contents,
+ uint64_t TID = llvm::get_threadid(), double Timestamp = 0) {
Contents["ts"] = Timestamp ? Timestamp : timestamp();
Contents["tid"] = int64_t(TID);
std::lock_guard<std::mutex> Lock(Mu);
@@ -80,9 +80,9 @@ public:
private:
class JSONSpan {
public:
- JSONSpan(JSONTracer *Tracer, StringRef Name, json::Object *Args)
+ JSONSpan(JSONTracer *Tracer, llvm::StringRef Name, llvm::json::Object *Args)
: StartTime(Tracer->timestamp()), EndTime(0), Name(Name),
- TID(get_threadid()), Tracer(Tracer), Args(Args) {
+ TID(llvm::get_threadid()), Tracer(Tracer), Args(Args) {
// ~JSONSpan() may run in a different thread, so we need to capture now.
Tracer->captureThreadMetadata();
@@ -100,26 +100,28 @@ private:
OriginTime = (*Parent)->StartTime;
auto FlowID = nextID();
- Tracer->jsonEvent("s",
- json::Object{{"id", FlowID},
- {"name", "Context crosses threads"},
- {"cat", "dummy"}},
- (*Parent)->TID, (*Parent)->StartTime);
- Tracer->jsonEvent("f",
- json::Object{{"id", FlowID},
- {"bp", "e"},
- {"name", "Context crosses threads"},
- {"cat", "dummy"}},
- TID);
+ Tracer->jsonEvent(
+ "s",
+ llvm::json::Object{{"id", FlowID},
+ {"name", "Context crosses threads"},
+ {"cat", "dummy"}},
+ (*Parent)->TID, (*Parent)->StartTime);
+ Tracer->jsonEvent(
+ "f",
+ llvm::json::Object{{"id", FlowID},
+ {"bp", "e"},
+ {"name", "Context crosses threads"},
+ {"cat", "dummy"}},
+ TID);
}
}
~JSONSpan() {
// Finally, record the event (ending at EndTime, not timestamp())!
Tracer->jsonEvent("X",
- json::Object{{"name", std::move(Name)},
- {"args", std::move(*Args)},
- {"dur", EndTime - StartTime}},
+ llvm::json::Object{{"name", std::move(Name)},
+ {"args", std::move(*Args)},
+ {"dur", EndTime - StartTime}},
TID, StartTime);
}
@@ -137,32 +139,34 @@ private:
std::string Name;
uint64_t TID;
JSONTracer *Tracer;
- json::Object *Args;
+ llvm::json::Object *Args;
};
static Key<std::unique_ptr<JSONSpan>> SpanKey;
// Record an event. ph and pid are set.
// Contents must be a list of the other JSON key/values.
- void rawEvent(StringRef Phase, json::Object &&Event) /*REQUIRES(Mu)*/ {
+ void rawEvent(llvm::StringRef Phase,
+ llvm::json::Object &&Event) /*REQUIRES(Mu)*/ {
// PID 0 represents the clangd process.
Event["pid"] = 0;
Event["ph"] = Phase;
- Out << Sep << formatv(JSONFormat, json::Value(std::move(Event)));
+ Out << Sep
+ << llvm::formatv(JSONFormat, llvm::json::Value(std::move(Event)));
Sep = ",\n";
}
// If we haven't already, emit metadata describing this thread.
void captureThreadMetadata() {
- uint64_t TID = get_threadid();
+ uint64_t TID = llvm::get_threadid();
std::lock_guard<std::mutex> Lock(Mu);
if (ThreadsWithMD.insert(TID).second) {
- SmallString<32> Name;
- get_thread_name(Name);
+ llvm::SmallString<32> Name;
+ llvm::get_thread_name(Name);
if (!Name.empty()) {
- rawEvent("M", json::Object{
+ rawEvent("M", llvm::json::Object{
{"tid", int64_t(TID)},
{"name", "thread_name"},
- {"args", json::Object{{"name", Name}}},
+ {"args", llvm::json::Object{{"name", Name}}},
});
}
}
@@ -174,10 +178,10 @@ private:
}
std::mutex Mu;
- raw_ostream &Out /*GUARDED_BY(Mu)*/;
+ llvm::raw_ostream &Out /*GUARDED_BY(Mu)*/;
const char *Sep /*GUARDED_BY(Mu)*/;
- DenseSet<uint64_t> ThreadsWithMD /*GUARDED_BY(Mu)*/;
- const sys::TimePoint<> Start;
+ llvm::DenseSet<uint64_t> ThreadsWithMD /*GUARDED_BY(Mu)*/;
+ const llvm::sys::TimePoint<> Start;
const char *JSONFormat;
};
@@ -193,31 +197,32 @@ Session::Session(EventTracer &Tracer) {
Session::~Session() { T = nullptr; }
-std::unique_ptr<EventTracer> createJSONTracer(raw_ostream &OS, bool Pretty) {
+std::unique_ptr<EventTracer> createJSONTracer(llvm::raw_ostream &OS,
+ bool Pretty) {
return llvm::make_unique<JSONTracer>(OS, Pretty);
}
-void log(const Twine &Message) {
+void log(const llvm::Twine &Message) {
if (!T)
return;
- T->instant("Log", json::Object{{"Message", Message.str()}});
+ T->instant("Log", llvm::json::Object{{"Message", Message.str()}});
}
// Returned context owns Args.
-static Context makeSpanContext(Twine Name, json::Object *Args) {
+static Context makeSpanContext(llvm::Twine Name, llvm::json::Object *Args) {
if (!T)
return Context::current().clone();
- WithContextValue WithArgs{std::unique_ptr<json::Object>(Args)};
+ WithContextValue WithArgs{std::unique_ptr<llvm::json::Object>(Args)};
return T->beginSpan(Name.isSingleStringRef() ? Name.getSingleStringRef()
- : StringRef(Name.str()),
+ : llvm::StringRef(Name.str()),
Args);
}
// Span keeps a non-owning pointer to the args, which is how users access them.
// The args are owned by the context though. They stick around until the
// beginSpan() context is destroyed, when the tracing engine will consume them.
-Span::Span(Twine Name)
- : Args(T ? new json::Object() : nullptr),
+Span::Span(llvm::Twine Name)
+ : Args(T ? new llvm::json::Object() : nullptr),
RestoreCtx(makeSpanContext(Name, Args)) {}
Span::~Span() {
diff --git a/clang-tools-extra/clangd/URI.cpp b/clang-tools-extra/clangd/URI.cpp
index 64540c66798..888acb7f21d 100644
--- a/clang-tools-extra/clangd/URI.cpp
+++ b/clang-tools-extra/clangd/URI.cpp
@@ -20,13 +20,13 @@
LLVM_INSTANTIATE_REGISTRY(clang::clangd::URISchemeRegistry)
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
-inline Error make_string_error(const Twine &Message) {
- return make_error<StringError>(Message, inconvertibleErrorCode());
+inline llvm::Error make_string_error(const llvm::Twine &Message) {
+ return llvm::make_error<llvm::StringError>(Message,
+ llvm::inconvertibleErrorCode());
}
/// \brief This manages file paths in the file system. All paths in the scheme
@@ -35,8 +35,9 @@ inline Error make_string_error(const Twine &Message) {
/// registry.
class FileSystemScheme : public URIScheme {
public:
- Expected<std::string> getAbsolutePath(StringRef /*Authority*/, StringRef Body,
- StringRef /*HintPath*/) const override {
+ llvm::Expected<std::string>
+ 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 '/': " +
@@ -44,26 +45,26 @@ public:
// For Windows paths e.g. /X:
if (Body.size() > 2 && Body[0] == '/' && Body[2] == ':')
Body.consume_front("/");
- SmallVector<char, 16> Path(Body.begin(), Body.end());
- sys::path::native(Path);
+ llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
+ llvm::sys::path::native(Path);
return std::string(Path.begin(), Path.end());
}
- Expected<URI> uriFromAbsolutePath(StringRef AbsolutePath) const override {
- using namespace llvm::sys;
-
+ llvm::Expected<URI>
+ uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
std::string Body;
// For Windows paths e.g. X:
if (AbsolutePath.size() > 1 && AbsolutePath[1] == ':')
Body = "/";
- Body += path::convert_to_slash(AbsolutePath);
+ Body += llvm::sys::path::convert_to_slash(AbsolutePath);
return URI("file", /*Authority=*/"", Body);
}
};
-Expected<std::unique_ptr<URIScheme>> findSchemeByName(StringRef Scheme) {
+llvm::Expected<std::unique_ptr<URIScheme>>
+findSchemeByName(llvm::StringRef Scheme) {
if (Scheme == "file")
- return make_unique<FileSystemScheme>();
+ return llvm::make_unique<FileSystemScheme>();
for (auto I = URISchemeRegistry::begin(), E = URISchemeRegistry::end();
I != E; ++I) {
@@ -96,12 +97,12 @@ bool shouldEscape(unsigned char C) {
/// - Unreserved characters are not escaped.
/// - Reserved characters always escaped with exceptions like '/'.
/// - All other characters are escaped.
-std::string percentEncode(StringRef Content) {
+std::string percentEncode(llvm::StringRef Content) {
std::string Result;
- raw_string_ostream OS(Result);
+ llvm::raw_string_ostream OS(Result);
for (unsigned char C : Content)
if (shouldEscape(C))
- OS << '%' << format_hex_no_prefix(C, 2, /*Upper = */ true);
+ OS << '%' << llvm::format_hex_no_prefix(C, 2, /*Upper = */ true);
else
OS << C;
@@ -110,16 +111,16 @@ std::string percentEncode(StringRef Content) {
}
/// Decodes a string according to percent-encoding.
-std::string percentDecode(StringRef Content) {
+std::string percentDecode(llvm::StringRef Content) {
std::string Result;
for (auto I = Content.begin(), E = Content.end(); I != E; ++I) {
if (*I != '%') {
Result += *I;
continue;
}
- if (*I == '%' && I + 2 < Content.end() && isHexDigit(*(I + 1)) &&
- isHexDigit(*(I + 2))) {
- Result.push_back(hexFromNibbles(*(I + 1), *(I + 2)));
+ if (*I == '%' && I + 2 < Content.end() && llvm::isHexDigit(*(I + 1)) &&
+ llvm::isHexDigit(*(I + 2))) {
+ Result.push_back(llvm::hexFromNibbles(*(I + 1), *(I + 2)));
I += 2;
} else
Result.push_back(*I);
@@ -127,19 +128,20 @@ std::string percentDecode(StringRef Content) {
return Result;
}
-bool isValidScheme(StringRef Scheme) {
+bool isValidScheme(llvm::StringRef Scheme) {
if (Scheme.empty())
return false;
- if (!isAlpha(Scheme[0]))
+ if (!llvm::isAlpha(Scheme[0]))
return false;
return std::all_of(Scheme.begin() + 1, Scheme.end(), [](char C) {
- return isAlnum(C) || C == '+' || C == '.' || C == '-';
+ return llvm::isAlnum(C) || C == '+' || C == '.' || C == '-';
});
}
} // namespace
-URI::URI(StringRef Scheme, StringRef Authority, StringRef Body)
+URI::URI(llvm::StringRef Scheme, llvm::StringRef Authority,
+ llvm::StringRef Body)
: Scheme(Scheme), Authority(Authority), Body(Body) {
assert(!Scheme.empty());
assert((Authority.empty() || Body.startswith("/")) &&
@@ -148,31 +150,31 @@ URI::URI(StringRef Scheme, StringRef Authority, StringRef Body)
std::string URI::toString() const {
std::string Result;
- raw_string_ostream OS(Result);
+ llvm::raw_string_ostream OS(Result);
OS << percentEncode(Scheme) << ":";
if (Authority.empty() && Body.empty())
return OS.str();
// If authority if empty, we only print body if it starts with "/"; otherwise,
// the URI is invalid.
- if (!Authority.empty() || StringRef(Body).startswith("/"))
+ if (!Authority.empty() || llvm::StringRef(Body).startswith("/"))
OS << "//" << percentEncode(Authority);
OS << percentEncode(Body);
OS.flush();
return Result;
}
-Expected<URI> URI::parse(StringRef OrigUri) {
+llvm::Expected<URI> URI::parse(llvm::StringRef OrigUri) {
URI U;
- StringRef Uri = OrigUri;
+ llvm::StringRef Uri = OrigUri;
auto Pos = Uri.find(':');
- if (Pos == StringRef::npos)
+ if (Pos == llvm::StringRef::npos)
return make_string_error("Scheme must be provided in URI: " + OrigUri);
auto SchemeStr = Uri.substr(0, Pos);
U.Scheme = percentDecode(SchemeStr);
if (!isValidScheme(U.Scheme))
- return make_string_error(
- formatv("Invalid scheme: {0} (decoded: {1})", SchemeStr, U.Scheme));
+ return make_string_error(llvm::formatv("Invalid scheme: {0} (decoded: {1})",
+ SchemeStr, U.Scheme));
Uri = Uri.substr(Pos + 1);
if (Uri.consume_front("//")) {
Pos = Uri.find('/');
@@ -183,8 +185,9 @@ Expected<URI> URI::parse(StringRef OrigUri) {
return U;
}
-Expected<URI> URI::create(StringRef AbsolutePath, StringRef Scheme) {
- if (!sys::path::is_absolute(AbsolutePath))
+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);
auto S = findSchemeByName(Scheme);
if (!S)
@@ -192,8 +195,8 @@ Expected<URI> URI::create(StringRef AbsolutePath, StringRef Scheme) {
return S->get()->uriFromAbsolutePath(AbsolutePath);
}
-URI URI::create(StringRef AbsolutePath) {
- if (!sys::path::is_absolute(AbsolutePath))
+URI URI::create(llvm::StringRef AbsolutePath) {
+ if (!llvm::sys::path::is_absolute(AbsolutePath))
llvm_unreachable(
("Not a valid absolute path: " + AbsolutePath).str().c_str());
for (auto &Entry : URISchemeRegistry::entries()) {
@@ -202,7 +205,7 @@ URI URI::create(StringRef AbsolutePath) {
// should be just skipped.
if (!URI) {
// Ignore the error.
- consumeError(URI.takeError());
+ llvm::consumeError(URI.takeError());
continue;
}
return std::move(*URI);
@@ -211,22 +214,24 @@ URI URI::create(StringRef AbsolutePath) {
return URI::createFile(AbsolutePath);
}
-URI URI::createFile(StringRef AbsolutePath) {
+URI URI::createFile(llvm::StringRef AbsolutePath) {
auto U = FileSystemScheme().uriFromAbsolutePath(AbsolutePath);
if (!U)
llvm_unreachable(llvm::toString(U.takeError()).c_str());
return std::move(*U);
}
-Expected<std::string> URI::resolve(const URI &Uri, StringRef HintPath) {
+llvm::Expected<std::string> URI::resolve(const URI &Uri,
+ llvm::StringRef HintPath) {
auto S = findSchemeByName(Uri.Scheme);
if (!S)
return S.takeError();
return S->get()->getAbsolutePath(Uri.Authority, Uri.Body, HintPath);
}
-Expected<std::string> URI::resolvePath(StringRef AbsPath, StringRef HintPath) {
- if (!sys::path::is_absolute(AbsPath))
+llvm::Expected<std::string> URI::resolvePath(llvm::StringRef AbsPath,
+ llvm::StringRef HintPath) {
+ if (!llvm::sys::path::is_absolute(AbsPath))
llvm_unreachable(("Not a valid absolute path: " + AbsPath).str().c_str());
for (auto &Entry : URISchemeRegistry::entries()) {
auto S = Entry.instantiate();
@@ -235,7 +240,7 @@ Expected<std::string> URI::resolvePath(StringRef AbsPath, StringRef HintPath) {
// should be just skipped.
if (!U) {
// Ignore the error.
- consumeError(U.takeError());
+ llvm::consumeError(U.takeError());
continue;
}
return S->getAbsolutePath(U->Authority, U->Body, HintPath);
@@ -244,7 +249,7 @@ Expected<std::string> URI::resolvePath(StringRef AbsPath, StringRef HintPath) {
return AbsPath;
}
-Expected<std::string> URI::includeSpelling(const URI &Uri) {
+llvm::Expected<std::string> URI::includeSpelling(const URI &Uri) {
auto S = findSchemeByName(Uri.Scheme);
if (!S)
return S.takeError();
diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp
index 37df307cb59..b07efe9d69d 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -18,7 +18,6 @@
#include "clang/Index/USRGeneration.h"
#include "llvm/Support/Path.h"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -46,7 +45,8 @@ void logIfOverflow(const SymbolLocation &Loc) {
// TUPath is used to resolve the path of URI.
// FIXME: figure out a good home for it, and share the implementation with
// FindSymbols.
-Optional<Location> toLSPLocation(const SymbolLocation &Loc, StringRef TUPath) {
+llvm::Optional<Location> toLSPLocation(const SymbolLocation &Loc,
+ llvm::StringRef TUPath) {
if (!Loc)
return None;
auto Uri = URI::parse(Loc.FileURI);
@@ -71,7 +71,7 @@ Optional<Location> toLSPLocation(const SymbolLocation &Loc, StringRef TUPath) {
}
struct MacroDecl {
- StringRef Name;
+ llvm::StringRef Name;
const MacroInfo *Info;
};
@@ -88,7 +88,7 @@ class DeclarationAndMacrosFinder : public index::IndexDataConsumer {
// explicitly in the code.
// True means the declaration is explicitly referenced at least once; false
// otherwise.
- DenseMap<const Decl *, bool> Decls;
+ llvm::DenseMap<const Decl *, bool> Decls;
const SourceLocation &SearchedLocation;
const ASTContext &AST;
Preprocessor &PP;
@@ -134,7 +134,7 @@ public:
bool
handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
- ArrayRef<index::SymbolRelation> Relations,
+ llvm::ArrayRef<index::SymbolRelation> Relations,
SourceLocation Loc,
index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
if (Loc == SearchedLocation) {
@@ -222,8 +222,8 @@ Range getTokenRange(ParsedAST &AST, SourceLocation TokLoc) {
sourceLocToPosition(SourceMgr, LocEnd)};
}
-Optional<Location> makeLocation(ParsedAST &AST, SourceLocation TokLoc,
- StringRef TUPath) {
+llvm::Optional<Location> makeLocation(ParsedAST &AST, SourceLocation TokLoc,
+ llvm::StringRef TUPath) {
const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
const FileEntry *F = SourceMgr.getFileEntryForID(SourceMgr.getFileID(TokLoc));
if (!F)
@@ -294,12 +294,12 @@ std::vector<Location> findDefinitions(ParsedAST &AST, Position Pos,
// 4. Return all populated locations for all symbols, definition first (
// which we think is the users wants most often).
struct CandidateLocation {
- Optional<Location> Def;
- Optional<Location> Decl;
+ llvm::Optional<Location> Def;
+ llvm::Optional<Location> Decl;
};
// We respect the order in Symbols.Decls.
- SmallVector<CandidateLocation, 8> ResultCandidates;
- DenseMap<SymbolID, size_t> CandidatesIndex;
+ llvm::SmallVector<CandidateLocation, 8> ResultCandidates;
+ llvm::DenseMap<SymbolID, size_t> CandidatesIndex;
// Emit all symbol locations (declaration or definition) from AST.
for (const DeclInfo &DI : Symbols.Decls) {
@@ -400,7 +400,7 @@ public:
bool
handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
- ArrayRef<index::SymbolRelation> Relations,
+ llvm::ArrayRef<index::SymbolRelation> Relations,
SourceLocation Loc,
index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
assert(D->isCanonicalDecl() && "expect D to be a canonical declaration");
@@ -412,7 +412,7 @@ public:
}
private:
- SmallSet<const Decl *, 4> CanonicalTargets;
+ llvm::SmallSet<const Decl *, 4> CanonicalTargets;
std::vector<Reference> References;
const ASTContext &AST;
};
@@ -478,7 +478,7 @@ static std::string typeDeclToString(const TypeDecl *TD) {
printingPolicyForDecls(TD->getASTContext().getPrintingPolicy());
std::string Name;
- raw_string_ostream Stream(Name);
+ llvm::raw_string_ostream Stream(Name);
Type.print(Stream, Policy);
return Stream.str();
@@ -487,12 +487,12 @@ static std::string typeDeclToString(const TypeDecl *TD) {
/// Return a string representation (e.g. "namespace ns1::ns2") of
/// the named declaration \p ND.
static std::string namedDeclQualifiedName(const NamedDecl *ND,
- StringRef Prefix) {
+ llvm::StringRef Prefix) {
PrintingPolicy Policy =
printingPolicyForDecls(ND->getASTContext().getPrintingPolicy());
std::string Name;
- raw_string_ostream Stream(Name);
+ llvm::raw_string_ostream Stream(Name);
Stream << Prefix << ' ';
ND->printQualifiedName(Stream, Policy);
@@ -502,7 +502,7 @@ static std::string namedDeclQualifiedName(const NamedDecl *ND,
/// Given a declaration \p D, return a human-readable string representing the
/// scope in which it is declared. If the declaration is in the global scope,
/// return the string "global namespace".
-static Optional<std::string> getScopeName(const Decl *D) {
+static llvm::Optional<std::string> getScopeName(const Decl *D) {
const DeclContext *DC = D->getDeclContext();
if (isa<TranslationUnitDecl>(DC))
@@ -520,7 +520,7 @@ static Optional<std::string> getScopeName(const Decl *D) {
/// Generate a \p Hover object given the declaration \p D.
static Hover getHoverContents(const Decl *D) {
Hover H;
- Optional<std::string> NamedScope = getScopeName(D);
+ llvm::Optional<std::string> NamedScope = getScopeName(D);
// Generate the "Declared in" section.
if (NamedScope) {
@@ -536,7 +536,7 @@ static Hover getHoverContents(const Decl *D) {
D = TD;
std::string DeclText;
- raw_string_ostream OS(DeclText);
+ llvm::raw_string_ostream OS(DeclText);
PrintingPolicy Policy =
printingPolicyForDecls(D->getASTContext().getPrintingPolicy());
@@ -553,7 +553,7 @@ static Hover getHoverContents(const Decl *D) {
static Hover getHoverContents(QualType T, ASTContext &ASTCtx) {
Hover H;
std::string TypeText;
- raw_string_ostream OS(TypeText);
+ llvm::raw_string_ostream OS(TypeText);
PrintingPolicy Policy = printingPolicyForDecls(ASTCtx.getPrintingPolicy());
T.print(OS, Policy);
OS.flush();
@@ -562,7 +562,7 @@ static Hover getHoverContents(QualType T, ASTContext &ASTCtx) {
}
/// Generate a \p Hover object given the macro \p MacroInf.
-static Hover getHoverContents(StringRef MacroName) {
+static Hover getHoverContents(llvm::StringRef MacroName) {
Hover H;
H.contents.value = "#define ";
@@ -582,13 +582,13 @@ namespace {
/// a deduced type set. The AST should be improved to simplify this scenario.
class DeducedTypeVisitor : public RecursiveASTVisitor<DeducedTypeVisitor> {
SourceLocation SearchedLocation;
- Optional<QualType> DeducedType;
+ llvm::Optional<QualType> DeducedType;
public:
DeducedTypeVisitor(SourceLocation SearchedLocation)
: SearchedLocation(SearchedLocation) {}
- Optional<QualType> getDeducedType() { return DeducedType; }
+ llvm::Optional<QualType> getDeducedType() { return DeducedType; }
// Handle auto initializers:
//- auto i = 1;
@@ -663,8 +663,8 @@ public:
} // namespace
/// Retrieves the deduced type at a given location (auto, decltype).
-Optional<QualType> getDeducedType(ParsedAST &AST,
- SourceLocation SourceLocationBeg) {
+llvm::Optional<QualType> getDeducedType(ParsedAST &AST,
+ SourceLocation SourceLocationBeg) {
Token Tok;
auto &ASTCtx = AST.getASTContext();
// Only try to find a deduced type if the token is auto or decltype.
@@ -683,7 +683,7 @@ Optional<QualType> getDeducedType(ParsedAST &AST,
return V.getDeducedType();
}
-Optional<Hover> getHover(ParsedAST &AST, Position Pos) {
+llvm::Optional<Hover> getHover(ParsedAST &AST, Position Pos) {
const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
SourceLocation SourceLocationBeg =
getBeginningOfIdentifier(AST, Pos, SourceMgr.getMainFileID());
diff --git a/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp b/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
index baedca2f105..d71f8fec68a 100644
--- a/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
+++ b/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
@@ -21,7 +21,6 @@
const char *IndexFilename;
const char *RequestsFilename;
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -41,16 +40,17 @@ std::vector<FuzzyFindRequest> extractQueriesFromLogs() {
std::istreambuf_iterator<char>());
std::vector<FuzzyFindRequest> Requests;
- auto JSONArray = json::parse(Log);
+ auto JSONArray = llvm::json::parse(Log);
// Panic if the provided file couldn't be parsed.
if (!JSONArray) {
- errs() << "Error when parsing JSON requests file: "
- << toString(JSONArray.takeError());
+ llvm::errs() << "Error when parsing JSON requests file: "
+ << llvm::toString(JSONArray.takeError());
exit(1);
}
if (!JSONArray->getAsArray()) {
- errs() << "Error: top-level value is not a JSON array: " << Log << '\n';
+ llvm::errs() << "Error: top-level value is not a JSON array: " << Log
+ << '\n';
exit(1);
}
@@ -58,7 +58,7 @@ std::vector<FuzzyFindRequest> extractQueriesFromLogs() {
FuzzyFindRequest Request;
// Panic if the provided file couldn't be parsed.
if (!fromJSON(Item, Request)) {
- errs() << "Error when deserializing request: " << Item << '\n';
+ llvm::errs() << "Error when deserializing request: " << Item << '\n';
exit(1);
}
Requests.push_back(Request);
@@ -94,9 +94,9 @@ BENCHMARK(DexQueries);
// FIXME(kbobyrev): Create a logger wrapper to suppress debugging info printer.
int main(int argc, char *argv[]) {
if (argc < 3) {
- errs() << "Usage: " << argv[0]
- << " global-symbol-index.yaml requests.json "
- "BENCHMARK_OPTIONS...\n";
+ llvm::errs() << "Usage: " << argv[0]
+ << " global-symbol-index.yaml requests.json "
+ "BENCHMARK_OPTIONS...\n";
return -1;
}
IndexFilename = argv[1];
diff --git a/clang-tools-extra/clangd/index/Background.cpp b/clang-tools-extra/clangd/index/Background.cpp
index 5db2d39f631..6a3eace664e 100644
--- a/clang-tools-extra/clangd/index/Background.cpp
+++ b/clang-tools-extra/clangd/index/Background.cpp
@@ -35,7 +35,6 @@
#include <string>
#include <thread>
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -119,11 +118,11 @@ createFileFilter(const llvm::StringMap<FileDigest> &FileDigests,
} // namespace
BackgroundIndex::BackgroundIndex(
- Context BackgroundContext, StringRef ResourceDir,
+ Context BackgroundContext, llvm::StringRef ResourceDir,
const FileSystemProvider &FSProvider, const GlobalCompilationDatabase &CDB,
BackgroundIndexStorage::Factory IndexStorageFactory,
size_t BuildIndexPeriodMs, size_t ThreadPoolSize)
- : SwapIndex(make_unique<MemIndex>()), ResourceDir(ResourceDir),
+ : SwapIndex(llvm::make_unique<MemIndex>()), ResourceDir(ResourceDir),
FSProvider(FSProvider), CDB(CDB),
BackgroundContext(std::move(BackgroundContext)),
BuildIndexPeriodMs(BuildIndexPeriodMs),
@@ -163,7 +162,7 @@ void BackgroundIndex::stop() {
void BackgroundIndex::run() {
WithContext Background(BackgroundContext.clone());
while (true) {
- Optional<Task> Task;
+ llvm::Optional<Task> Task;
ThreadPriority Priority;
{
std::unique_lock<std::mutex> Lock(QueueMu);
@@ -260,15 +259,15 @@ void BackgroundIndex::enqueueTask(Task T, ThreadPriority Priority) {
}
/// Given index results from a TU, only update files in \p FilesToUpdate.
-void BackgroundIndex::update(StringRef MainFile, IndexFileIn Index,
- const StringMap<FileDigest> &FilesToUpdate,
+void BackgroundIndex::update(llvm::StringRef MainFile, IndexFileIn Index,
+ const llvm::StringMap<FileDigest> &FilesToUpdate,
BackgroundIndexStorage *IndexStorage) {
// Partition symbols/references into files.
struct File {
- DenseSet<const Symbol *> Symbols;
- DenseSet<const Ref *> Refs;
+ llvm::DenseSet<const Symbol *> Symbols;
+ llvm::DenseSet<const Ref *> Refs;
};
- StringMap<File> Files;
+ llvm::StringMap<File> Files;
URIToFileCache URICache(MainFile);
for (const auto &Sym : *Index.Symbols) {
if (Sym.CanonicalDeclaration) {
@@ -287,7 +286,7 @@ void BackgroundIndex::update(StringRef MainFile, IndexFileIn Index,
Files[DefPath].Symbols.insert(&Sym);
}
}
- DenseMap<const Ref *, SymbolID> RefToIDs;
+ llvm::DenseMap<const Ref *, SymbolID> RefToIDs;
for (const auto &SymRefs : *Index.Refs) {
for (const auto &R : SymRefs.second) {
auto Path = URICache.resolve(R.Location.FileURI);
@@ -301,7 +300,7 @@ void BackgroundIndex::update(StringRef MainFile, IndexFileIn Index,
// Build and store new slabs for each updated file.
for (const auto &F : Files) {
- StringRef Path = F.first();
+ llvm::StringRef Path = F.first();
vlog("Update symbols in {0}", Path);
SymbolSlab::Builder Syms;
RefSlab::Builder Refs;
@@ -362,22 +361,22 @@ void BackgroundIndex::buildIndex() {
}
}
-Error BackgroundIndex::index(tooling::CompileCommand Cmd,
- BackgroundIndexStorage *IndexStorage) {
+llvm::Error BackgroundIndex::index(tooling::CompileCommand Cmd,
+ BackgroundIndexStorage *IndexStorage) {
trace::Span Tracer("BackgroundIndex");
SPAN_ATTACH(Tracer, "file", Cmd.Filename);
- SmallString<128> AbsolutePath;
- if (sys::path::is_absolute(Cmd.Filename)) {
+ llvm::SmallString<128> AbsolutePath;
+ if (llvm::sys::path::is_absolute(Cmd.Filename)) {
AbsolutePath = Cmd.Filename;
} else {
AbsolutePath = Cmd.Directory;
- sys::path::append(AbsolutePath, Cmd.Filename);
+ llvm::sys::path::append(AbsolutePath, Cmd.Filename);
}
auto FS = FSProvider.getFileSystem();
auto Buf = FS->getBufferForFile(AbsolutePath);
if (!Buf)
- return errorCodeToError(Buf.getError());
+ return llvm::errorCodeToError(Buf.getError());
auto Hash = digest(Buf->get()->getBuffer());
// Take a snapshot of the digests to avoid locking for each file in the TU.
@@ -386,31 +385,31 @@ Error BackgroundIndex::index(tooling::CompileCommand Cmd,
std::lock_guard<std::mutex> Lock(DigestsMu);
if (IndexedFileDigests.lookup(AbsolutePath) == Hash) {
vlog("No need to index {0}, already up to date", AbsolutePath);
- return Error::success();
+ return llvm::Error::success();
}
DigestsSnapshot = IndexedFileDigests;
}
- log("Indexing {0} (digest:={1})", Cmd.Filename, toHex(Hash));
+ log("Indexing {0} (digest:={1})", Cmd.Filename, llvm::toHex(Hash));
ParseInputs Inputs;
Inputs.FS = std::move(FS);
Inputs.FS->setCurrentWorkingDirectory(Cmd.Directory);
Inputs.CompileCommand = std::move(Cmd);
auto CI = buildCompilerInvocation(Inputs);
if (!CI)
- return createStringError(inconvertibleErrorCode(),
- "Couldn't build compiler invocation");
+ return llvm::createStringError(llvm::inconvertibleErrorCode(),
+ "Couldn't build compiler invocation");
IgnoreDiagnostics IgnoreDiags;
auto Clang = prepareCompilerInstance(
std::move(CI), /*Preamble=*/nullptr, std::move(*Buf),
std::make_shared<PCHContainerOperations>(), Inputs.FS, IgnoreDiags);
if (!Clang)
- return createStringError(inconvertibleErrorCode(),
- "Couldn't build compiler instance");
+ return llvm::createStringError(llvm::inconvertibleErrorCode(),
+ "Couldn't build compiler instance");
SymbolCollector::Options IndexOpts;
- StringMap<FileDigest> FilesToUpdate;
+ llvm::StringMap<FileDigest> FilesToUpdate;
IndexOpts.FileFilter = createFileFilter(DigestsSnapshot, FilesToUpdate);
IndexFileIn Index;
auto Action = createStaticIndexingAction(
@@ -425,15 +424,17 @@ Error BackgroundIndex::index(tooling::CompileCommand Cmd,
const FrontendInputFile &Input = Clang->getFrontendOpts().Inputs.front();
if (!Action->BeginSourceFile(*Clang, Input))
- return createStringError(inconvertibleErrorCode(),
- "BeginSourceFile() failed");
+ return llvm::createStringError(llvm::inconvertibleErrorCode(),
+ "BeginSourceFile() failed");
if (!Action->Execute())
- return createStringError(inconvertibleErrorCode(), "Execute() failed");
+ return llvm::createStringError(llvm::inconvertibleErrorCode(),
+ "Execute() failed");
Action->EndSourceFile();
if (Clang->hasDiagnostics() &&
Clang->getDiagnostics().hasUncompilableErrorOccurred()) {
- return createStringError(inconvertibleErrorCode(),
- "IndexingAction failed: has uncompilable errors");
+ return llvm::createStringError(
+ llvm::inconvertibleErrorCode(),
+ "IndexingAction failed: has uncompilable errors");
}
assert(Index.Symbols && Index.Refs && Index.Sources
@@ -460,7 +461,7 @@ Error BackgroundIndex::index(tooling::CompileCommand Cmd,
reset(
IndexedSymbols.buildIndex(IndexType::Light, DuplicateHandling::Merge));
- return Error::success();
+ return llvm::Error::success();
}
} // namespace clangd
diff --git a/clang-tools-extra/clangd/index/CanonicalIncludes.cpp b/clang-tools-extra/clangd/index/CanonicalIncludes.cpp
index 0cc44feb2ac..7351b861a22 100644
--- a/clang-tools-extra/clangd/index/CanonicalIncludes.cpp
+++ b/clang-tools-extra/clangd/index/CanonicalIncludes.cpp
@@ -13,49 +13,50 @@
#include "llvm/Support/Path.h"
#include <algorithm>
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
const char IWYUPragma[] = "// IWYU pragma: private, include ";
} // namespace
-void CanonicalIncludes::addPathSuffixMapping(StringRef Suffix,
- StringRef CanonicalPath) {
- int Components =
- std::distance(sys::path::begin(Suffix), sys::path::end(Suffix));
+void CanonicalIncludes::addPathSuffixMapping(llvm::StringRef Suffix,
+ llvm::StringRef CanonicalPath) {
+ int Components = std::distance(llvm::sys::path::begin(Suffix),
+ llvm::sys::path::end(Suffix));
MaxSuffixComponents = std::max(MaxSuffixComponents, Components);
SuffixHeaderMapping[Suffix] = CanonicalPath;
}
-void CanonicalIncludes::addMapping(StringRef Path, StringRef CanonicalPath) {
+void CanonicalIncludes::addMapping(llvm::StringRef Path,
+ llvm::StringRef CanonicalPath) {
FullPathMapping[Path] = CanonicalPath;
}
-void CanonicalIncludes::addSymbolMapping(StringRef QualifiedName,
- StringRef CanonicalPath) {
+void CanonicalIncludes::addSymbolMapping(llvm::StringRef QualifiedName,
+ llvm::StringRef CanonicalPath) {
this->SymbolMapping[QualifiedName] = CanonicalPath;
}
-StringRef CanonicalIncludes::mapHeader(ArrayRef<std::string> Headers,
- StringRef QualifiedName) const {
+llvm::StringRef
+CanonicalIncludes::mapHeader(llvm::ArrayRef<std::string> Headers,
+ llvm::StringRef QualifiedName) const {
assert(!Headers.empty());
auto SE = SymbolMapping.find(QualifiedName);
if (SE != SymbolMapping.end())
return SE->second;
// Find the first header such that the extension is not '.inc', and isn't a
// recognized non-header file
- auto I = llvm::find_if(Headers, [](StringRef Include) {
+ auto I = llvm::find_if(Headers, [](llvm::StringRef Include) {
// Skip .inc file whose including header file should
// be #included instead.
return !Include.endswith(".inc");
});
if (I == Headers.end())
return Headers[0]; // Fallback to the declaring header.
- StringRef Header = *I;
+ llvm::StringRef Header = *I;
// If Header is not expected be included (e.g. .cc file), we fall back to
// the declaring header.
- StringRef Ext = sys::path::extension(Header).trim('.');
+ llvm::StringRef Ext = llvm::sys::path::extension(Header).trim('.');
// Include-able headers must have precompile type. Treat files with
// non-recognized extenstions (TY_INVALID) as headers.
auto ExtType = driver::types::lookupTypeForExtension(Ext);
@@ -68,7 +69,8 @@ StringRef CanonicalIncludes::mapHeader(ArrayRef<std::string> Headers,
return MapIt->second;
int Components = 1;
- for (auto It = sys::path::rbegin(Header), End = sys::path::rend(Header);
+ for (auto It = llvm::sys::path::rbegin(Header),
+ End = llvm::sys::path::rend(Header);
It != End && Components <= MaxSuffixComponents; ++It, ++Components) {
auto SubPath = Header.substr(It->data() - Header.begin());
auto MappingIt = SuffixHeaderMapping.find(SubPath);
@@ -85,7 +87,7 @@ collectIWYUHeaderMaps(CanonicalIncludes *Includes) {
PragmaCommentHandler(CanonicalIncludes *Includes) : Includes(Includes) {}
bool HandleComment(Preprocessor &PP, SourceRange Range) override {
- StringRef Text =
+ llvm::StringRef Text =
Lexer::getSourceText(CharSourceRange::getCharRange(Range),
PP.getSourceManager(), PP.getLangOpts());
if (!Text.consume_front(IWYUPragma))
diff --git a/clang-tools-extra/clangd/index/FileIndex.cpp b/clang-tools-extra/clangd/index/FileIndex.cpp
index b944c72d850..d3e3596dbec 100644
--- a/clang-tools-extra/clangd/index/FileIndex.cpp
+++ b/clang-tools-extra/clangd/index/FileIndex.cpp
@@ -24,13 +24,12 @@
#include "llvm/ADT/StringRef.h"
#include <memory>
-using namespace llvm;
namespace clang {
namespace clangd {
static std::pair<SymbolSlab, RefSlab>
indexSymbols(ASTContext &AST, std::shared_ptr<Preprocessor> PP,
- ArrayRef<Decl *> DeclsToIndex, bool IsIndexMainAST) {
+ llvm::ArrayRef<Decl *> DeclsToIndex, bool IsIndexMainAST) {
SymbolCollector::Options CollectorOpts;
// FIXME(ioeric): we might also want to collect include headers. We would need
// to make sure all includes are canonicalized (with CanonicalIncludes), which
@@ -116,7 +115,7 @@ FileSymbols::buildIndex(IndexType Type, DuplicateHandling DuplicateHandle) {
std::vector<Symbol> SymsStorage;
switch (DuplicateHandle) {
case DuplicateHandling::Merge: {
- DenseMap<SymbolID, Symbol> Merged;
+ llvm::DenseMap<SymbolID, Symbol> Merged;
for (const auto &Slab : SymbolSlabs) {
for (const auto &Sym : *Slab) {
auto I = Merged.try_emplace(Sym.ID, Sym);
@@ -143,9 +142,9 @@ FileSymbols::buildIndex(IndexType Type, DuplicateHandling DuplicateHandle) {
}
std::vector<Ref> RefsStorage; // Contiguous ranges for each SymbolID.
- DenseMap<SymbolID, ArrayRef<Ref>> AllRefs;
+ llvm::DenseMap<SymbolID, llvm::ArrayRef<Ref>> AllRefs;
{
- DenseMap<SymbolID, SmallVector<Ref, 4>> MergedRefs;
+ llvm::DenseMap<SymbolID, llvm::SmallVector<Ref, 4>> MergedRefs;
size_t Count = 0;
for (const auto &RefSlab : RefSlabs)
for (const auto &Sym : *RefSlab) {
@@ -161,8 +160,8 @@ FileSymbols::buildIndex(IndexType Type, DuplicateHandling DuplicateHandle) {
llvm::copy(SymRefs, back_inserter(RefsStorage));
AllRefs.try_emplace(
Sym.first,
- ArrayRef<Ref>(&RefsStorage[RefsStorage.size() - SymRefs.size()],
- SymRefs.size()));
+ llvm::ArrayRef<Ref>(&RefsStorage[RefsStorage.size() - SymRefs.size()],
+ SymRefs.size()));
}
}
@@ -177,13 +176,13 @@ FileSymbols::buildIndex(IndexType Type, DuplicateHandling DuplicateHandle) {
switch (Type) {
case IndexType::Light:
return llvm::make_unique<MemIndex>(
- make_pointee_range(AllSymbols), std::move(AllRefs),
+ llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
std::move(RefsStorage), std::move(SymsStorage)),
StorageSize);
case IndexType::Heavy:
return llvm::make_unique<dex::Dex>(
- make_pointee_range(AllSymbols), std::move(AllRefs),
+ llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
std::move(RefsStorage), std::move(SymsStorage)),
StorageSize);
diff --git a/clang-tools-extra/clangd/index/Index.cpp b/clang-tools-extra/clangd/index/Index.cpp
index dd4b5eb32a7..4036d671827 100644
--- a/clang-tools-extra/clangd/index/Index.cpp
+++ b/clang-tools-extra/clangd/index/Index.cpp
@@ -14,7 +14,6 @@
#include "llvm/Support/Error.h"
#include "llvm/Support/raw_ostream.h"
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -35,14 +34,14 @@ void SymbolLocation::Position::setColumn(uint32_t Col) {
Column = Col;
}
-raw_ostream &operator<<(raw_ostream &OS, const SymbolLocation &L) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const SymbolLocation &L) {
if (!L)
return OS << "(none)";
return OS << L.FileURI << "[" << L.Start.line() << ":" << L.Start.column()
<< "-" << L.End.line() << ":" << L.End.column() << ")";
}
-raw_ostream &operator<<(raw_ostream &OS, SymbolOrigin O) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, SymbolOrigin O) {
if (O == SymbolOrigin::Unknown)
return OS << "unknown";
constexpr static char Sigils[] = "ADSM4567";
@@ -52,7 +51,7 @@ raw_ostream &operator<<(raw_ostream &OS, SymbolOrigin O) {
return OS;
}
-raw_ostream &operator<<(raw_ostream &OS, Symbol::SymbolFlag F) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, Symbol::SymbolFlag F) {
if (F == Symbol::None)
return OS << "None";
std::string s;
@@ -60,10 +59,10 @@ raw_ostream &operator<<(raw_ostream &OS, Symbol::SymbolFlag F) {
s += "deprecated|";
if (F & Symbol::IndexedForCodeCompletion)
s += "completion|";
- return OS << StringRef(s).rtrim('|');
+ return OS << llvm::StringRef(s).rtrim('|');
}
-raw_ostream &operator<<(raw_ostream &OS, const Symbol &S) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Symbol &S) {
return OS << S.Scope << S.Name;
}
@@ -85,8 +84,8 @@ SymbolSlab::const_iterator SymbolSlab::find(const SymbolID &ID) const {
}
// Copy the underlying data of the symbol into the owned arena.
-static void own(Symbol &S, UniqueStringSaver &Strings) {
- visitStrings(S, [&](StringRef &V) { V = Strings.save(V); });
+static void own(Symbol &S, llvm::UniqueStringSaver &Strings) {
+ visitStrings(S, [&](llvm::StringRef &V) { V = Strings.save(V); });
}
void SymbolSlab::Builder::insert(const Symbol &S) {
@@ -106,14 +105,14 @@ SymbolSlab SymbolSlab::Builder::build() && {
llvm::sort(Symbols,
[](const Symbol &L, const Symbol &R) { return L.ID < R.ID; });
// We may have unused strings from overwritten symbols. Build a new arena.
- BumpPtrAllocator NewArena;
- UniqueStringSaver Strings(NewArena);
+ llvm::BumpPtrAllocator NewArena;
+ llvm::UniqueStringSaver Strings(NewArena);
for (auto &S : Symbols)
own(S, Strings);
return SymbolSlab(std::move(NewArena), std::move(Symbols));
}
-raw_ostream &operator<<(raw_ostream &OS, RefKind K) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, RefKind K) {
if (K == RefKind::Unknown)
return OS << "Unknown";
static const std::vector<const char *> Messages = {"Decl", "Def", "Ref"};
@@ -129,7 +128,7 @@ raw_ostream &operator<<(raw_ostream &OS, RefKind K) {
return OS;
}
-raw_ostream &operator<<(raw_ostream &OS, const Ref &R) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Ref &R) {
return OS << R.Location << ":" << R.Kind;
}
@@ -143,7 +142,7 @@ void RefSlab::Builder::insert(const SymbolID &ID, const Ref &S) {
RefSlab RefSlab::Builder::build() && {
// We can reuse the arena, as it only has unique strings and we need them all.
// Reallocate refs on the arena to reduce waste and indirections when reading.
- std::vector<std::pair<SymbolID, ArrayRef<Ref>>> Result;
+ std::vector<std::pair<SymbolID, llvm::ArrayRef<Ref>>> Result;
Result.reserve(Refs.size());
size_t NumRefs = 0;
for (auto &Sym : Refs) {
@@ -155,7 +154,7 @@ RefSlab RefSlab::Builder::build() && {
NumRefs += SymRefs.size();
auto *Array = Arena.Allocate<Ref>(SymRefs.size());
std::uninitialized_copy(SymRefs.begin(), SymRefs.end(), Array);
- Result.emplace_back(Sym.first, ArrayRef<Ref>(Array, SymRefs.size()));
+ Result.emplace_back(Sym.first, llvm::ArrayRef<Ref>(Array, SymRefs.size()));
}
return RefSlab(std::move(Result), std::move(Arena), NumRefs);
}
@@ -174,8 +173,8 @@ std::shared_ptr<SymbolIndex> SwapIndex::snapshot() const {
return Index;
}
-bool fromJSON(const json::Value &Parameters, FuzzyFindRequest &Request) {
- json::ObjectMapper O(Parameters);
+bool fromJSON(const llvm::json::Value &Parameters, FuzzyFindRequest &Request) {
+ llvm::json::ObjectMapper O(Parameters);
int64_t Limit;
bool OK =
O && O.map("Query", Request.Query) && O.map("Scopes", Request.Scopes) &&
@@ -187,27 +186,27 @@ bool fromJSON(const json::Value &Parameters, FuzzyFindRequest &Request) {
return OK;
}
-json::Value toJSON(const FuzzyFindRequest &Request) {
- return json::Object{
+llvm::json::Value toJSON(const FuzzyFindRequest &Request) {
+ return llvm::json::Object{
{"Query", Request.Query},
- {"Scopes", json::Array{Request.Scopes}},
+ {"Scopes", llvm::json::Array{Request.Scopes}},
{"AnyScope", Request.AnyScope},
{"Limit", Request.Limit},
{"RestrictForCodeCompletion", Request.RestrictForCodeCompletion},
- {"ProximityPaths", json::Array{Request.ProximityPaths}},
+ {"ProximityPaths", llvm::json::Array{Request.ProximityPaths}},
};
}
bool SwapIndex::fuzzyFind(const FuzzyFindRequest &R,
- function_ref<void(const Symbol &)> CB) const {
+ llvm::function_ref<void(const Symbol &)> CB) const {
return snapshot()->fuzzyFind(R, CB);
}
void SwapIndex::lookup(const LookupRequest &R,
- function_ref<void(const Symbol &)> CB) const {
+ llvm::function_ref<void(const Symbol &)> CB) const {
return snapshot()->lookup(R, CB);
}
void SwapIndex::refs(const RefsRequest &R,
- function_ref<void(const Ref &)> CB) const {
+ llvm::function_ref<void(const Ref &)> CB) const {
return snapshot()->refs(R, CB);
}
size_t SwapIndex::estimateMemoryUsage() const {
diff --git a/clang-tools-extra/clangd/index/IndexAction.cpp b/clang-tools-extra/clangd/index/IndexAction.cpp
index 63e1155f318..a6df64b7be3 100644
--- a/clang-tools-extra/clangd/index/IndexAction.cpp
+++ b/clang-tools-extra/clangd/index/IndexAction.cpp
@@ -4,7 +4,6 @@
#include "clang/Index/IndexingAction.h"
#include "clang/Tooling/Tooling.h"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -63,10 +62,10 @@ public:
// Add edges from including files to includes.
void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
- StringRef FileName, bool IsAngled,
+ llvm::StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange, const FileEntry *File,
- StringRef SearchPath, StringRef RelativePath,
- const Module *Imported,
+ llvm::StringRef SearchPath,
+ llvm::StringRef RelativePath, const Module *Imported,
SrcMgr::CharacteristicKind FileType) override {
auto IncludeURI = toURI(File);
if (!IncludeURI)
@@ -116,8 +115,8 @@ public:
Includes(std::move(Includes)),
PragmaHandler(collectIWYUHeaderMaps(this->Includes.get())) {}
- std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
- StringRef InFile) override {
+ std::unique_ptr<ASTConsumer>
+ CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
CI.getPreprocessor().addCommentHandler(PragmaHandler.get());
if (IncludeGraphCallback != nullptr)
CI.getPreprocessor().addPPCallbacks(
@@ -137,7 +136,7 @@ public:
const auto &CI = getCompilerInstance();
if (CI.hasDiagnostics() &&
CI.getDiagnostics().hasUncompilableErrorOccurred()) {
- errs() << "Skipping TU due to uncompilable errors\n";
+ llvm::errs() << "Skipping TU due to uncompilable errors\n";
return;
}
SymbolsCallback(Collector->takeSymbols());
diff --git a/clang-tools-extra/clangd/index/MemIndex.cpp b/clang-tools-extra/clangd/index/MemIndex.cpp
index 42340e8eeb9..35352e6e686 100644
--- a/clang-tools-extra/clangd/index/MemIndex.cpp
+++ b/clang-tools-extra/clangd/index/MemIndex.cpp
@@ -13,7 +13,6 @@
#include "Quality.h"
#include "Trace.h"
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -25,8 +24,9 @@ std::unique_ptr<SymbolIndex> MemIndex::build(SymbolSlab Slab, RefSlab Refs) {
BackingDataSize);
}
-bool MemIndex::fuzzyFind(const FuzzyFindRequest &Req,
- function_ref<void(const Symbol &)> Callback) const {
+bool MemIndex::fuzzyFind(
+ const FuzzyFindRequest &Req,
+ llvm::function_ref<void(const Symbol &)> Callback) const {
assert(!StringRef(Req.Query).contains("::") &&
"There must be no :: in query.");
trace::Span Tracer("MemIndex fuzzyFind");
@@ -39,7 +39,7 @@ bool MemIndex::fuzzyFind(const FuzzyFindRequest &Req,
const Symbol *Sym = Pair.second;
// Exact match against all possible scopes.
- if (!Req.AnyScope && !is_contained(Req.Scopes, Sym->Scope))
+ if (!Req.AnyScope && !llvm::is_contained(Req.Scopes, Sym->Scope))
continue;
if (Req.RestrictForCodeCompletion &&
!(Sym->Flags & Symbol::IndexedForCodeCompletion))
@@ -57,7 +57,7 @@ bool MemIndex::fuzzyFind(const FuzzyFindRequest &Req,
}
void MemIndex::lookup(const LookupRequest &Req,
- function_ref<void(const Symbol &)> Callback) const {
+ llvm::function_ref<void(const Symbol &)> Callback) const {
trace::Span Tracer("MemIndex lookup");
for (const auto &ID : Req.IDs) {
auto I = Index.find(ID);
@@ -67,7 +67,7 @@ void MemIndex::lookup(const LookupRequest &Req,
}
void MemIndex::refs(const RefsRequest &Req,
- function_ref<void(const Ref &)> Callback) const {
+ llvm::function_ref<void(const Ref &)> Callback) const {
trace::Span Tracer("MemIndex refs");
for (const auto &ReqID : Req.IDs) {
auto SymRefs = Refs.find(ReqID);
diff --git a/clang-tools-extra/clangd/index/Merge.cpp b/clang-tools-extra/clangd/index/Merge.cpp
index 0510b7ad3ac..f599d757aa8 100644
--- a/clang-tools-extra/clangd/index/Merge.cpp
+++ b/clang-tools-extra/clangd/index/Merge.cpp
@@ -14,7 +14,6 @@
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/raw_ostream.h"
-using namespace llvm;
namespace clang {
namespace clangd {
@@ -23,8 +22,9 @@ namespace clangd {
// - find the generating file from each Symbol which is Static-only
// - ask Dynamic if it has that file (needs new SymbolIndex method)
// - if so, drop the Symbol.
-bool MergedIndex::fuzzyFind(const FuzzyFindRequest &Req,
- function_ref<void(const Symbol &)> Callback) const {
+bool MergedIndex::fuzzyFind(
+ const FuzzyFindRequest &Req,
+ llvm::function_ref<void(const Symbol &)> Callback) const {
// We can't step through both sources in parallel. So:
// 1) query all dynamic symbols, slurping results into a slab
// 2) query the static symbols, for each one:
@@ -43,7 +43,7 @@ bool MergedIndex::fuzzyFind(const FuzzyFindRequest &Req,
});
SymbolSlab Dyn = std::move(DynB).build();
- DenseSet<SymbolID> SeenDynamicSymbols;
+ llvm::DenseSet<SymbolID> SeenDynamicSymbols;
More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
auto DynS = Dyn.find(S.ID);
++StaticCount;
@@ -62,8 +62,9 @@ bool MergedIndex::fuzzyFind(const FuzzyFindRequest &Req,
return More;
}
-void MergedIndex::lookup(const LookupRequest &Req,
- function_ref<void(const Symbol &)> Callback) const {
+void MergedIndex::lookup(
+ const LookupRequest &Req,
+ llvm::function_ref<void(const Symbol &)> Callback) const {
trace::Span Tracer("MergedIndex lookup");
SymbolSlab::Builder B;
@@ -84,7 +85,7 @@ void MergedIndex::lookup(const LookupRequest &Req,
}
void MergedIndex::refs(const RefsRequest &Req,
- function_ref<void(const Ref &)> Callback) const {
+ llvm::function_ref<void(const Ref &)> Callback) const {
trace::Span Tracer("MergedIndex refs");
// We don't want duplicated refs from the static/dynamic indexes,
// and we can't reliably duplicate them because offsets may differ slightly.
@@ -94,7 +95,7 @@ void MergedIndex::refs(const RefsRequest &Req,
// FIXME: The heuristic fails if the dynamic index contains a file, but all
// refs were removed (we will report stale ones from the static index).
// Ultimately we should explicit check which index has the file instead.
- StringSet<> DynamicIndexFileURIs;
+ llvm::StringSet<> DynamicIndexFileURIs;
Dynamic->refs(Req, [&](const Ref &O) {
DynamicIndexFileURIs.insert(O.Location.FileURI);
Callback(O);
diff --git a/clang-tools-extra/clangd/index/Serialization.cpp b/clang-tools-extra/clangd/index/Serialization.cpp
index 1d17a42c486..a4f99b1cb29 100644
--- a/clang-tools-extra/clangd/index/Serialization.cpp
+++ b/clang-tools-extra/clangd/index/Serialization.cpp
@@ -17,12 +17,12 @@
#include "llvm/Support/Endian.h"
#include "llvm/Support/Error.h"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
-Error makeError(const Twine &Msg) {
- return make_error<StringError>(Msg, inconvertibleErrorCode());
+llvm::Error makeError(const llvm::Twine &Msg) {
+ return llvm::make_error<llvm::StringError>(Msg,
+ llvm::inconvertibleErrorCode());
}
// IO PRIMITIVES
@@ -40,14 +40,14 @@ class Reader {
bool Err = false;
public:
- Reader(StringRef Data) : Begin(Data.begin()), End(Data.end()) {}
+ Reader(llvm::StringRef Data) : Begin(Data.begin()), End(Data.end()) {}
// The "error" bit is set by reading past EOF or reading invalid data.
// When in an error state, reads may return zero values: callers should check.
bool err() const { return Err; }
// Did we read all the data, or encounter an error?
bool eof() const { return Begin == End || Err; }
// All the data we didn't read yet.
- StringRef rest() const { return StringRef(Begin, End - Begin); }
+ llvm::StringRef rest() const { return llvm::StringRef(Begin, End - Begin); }
uint8_t consume8() {
if (LLVM_UNLIKELY(Begin == End)) {
@@ -62,17 +62,17 @@ public:
Err = true;
return 0;
}
- auto Ret = support::endian::read32le(Begin);
+ auto Ret = llvm::support::endian::read32le(Begin);
Begin += 4;
return Ret;
}
- StringRef consume(int N) {
+ llvm::StringRef consume(int N) {
if (LLVM_UNLIKELY(Begin + N > End)) {
Err = true;
- return StringRef();
+ return llvm::StringRef();
}
- StringRef Ret(Begin, N);
+ llvm::StringRef Ret(Begin, N);
Begin += N;
return Ret;
}
@@ -90,28 +90,28 @@ public:
return Val;
}
- StringRef consumeString(ArrayRef<StringRef> Strings) {
+ llvm::StringRef consumeString(llvm::ArrayRef<llvm::StringRef> Strings) {
auto StringIndex = consumeVar();
if (LLVM_UNLIKELY(StringIndex >= Strings.size())) {
Err = true;
- return StringRef();
+ return llvm::StringRef();
}
return Strings[StringIndex];
}
SymbolID consumeID() {
- StringRef Raw = consume(SymbolID::RawSize); // short if truncated.
+ llvm::StringRef Raw = consume(SymbolID::RawSize); // short if truncated.
return LLVM_UNLIKELY(err()) ? SymbolID() : SymbolID::fromRaw(Raw);
}
};
-void write32(uint32_t I, raw_ostream &OS) {
+void write32(uint32_t I, llvm::raw_ostream &OS) {
char buf[4];
- support::endian::write32le(buf, I);
+ llvm::support::endian::write32le(buf, I);
OS.write(buf, sizeof(buf));
}
-void writeVar(uint32_t I, raw_ostream &OS) {
+void writeVar(uint32_t I, llvm::raw_ostream &OS) {
constexpr static uint8_t More = 1 << 7;
if (LLVM_LIKELY(I < 1 << 7)) {
OS.write(I);
@@ -142,10 +142,10 @@ void writeVar(uint32_t I, raw_ostream &OS) {
// Maps each string to a canonical representation.
// Strings remain owned externally (e.g. by SymbolSlab).
class StringTableOut {
- DenseSet<StringRef> Unique;
- std::vector<StringRef> Sorted;
+ llvm::DenseSet<llvm::StringRef> Unique;
+ std::vector<llvm::StringRef> Sorted;
// Since strings are interned, look up can be by pointer.
- DenseMap<std::pair<const char *, size_t>, unsigned> Index;
+ llvm::DenseMap<std::pair<const char *, size_t>, unsigned> Index;
public:
StringTableOut() {
@@ -154,22 +154,22 @@ public:
Unique.insert("");
}
// Add a string to the table. Overwrites S if an identical string exists.
- void intern(StringRef &S) { S = *Unique.insert(S).first; };
+ void intern(llvm::StringRef &S) { S = *Unique.insert(S).first; };
// Finalize the table and write it to OS. No more strings may be added.
- void finalize(raw_ostream &OS) {
+ void finalize(llvm::raw_ostream &OS) {
Sorted = {Unique.begin(), Unique.end()};
llvm::sort(Sorted);
for (unsigned I = 0; I < Sorted.size(); ++I)
Index.try_emplace({Sorted[I].data(), Sorted[I].size()}, I);
std::string RawTable;
- for (StringRef S : Sorted) {
+ for (llvm::StringRef S : Sorted) {
RawTable.append(S);
RawTable.push_back(0);
}
- if (zlib::isAvailable()) {
- SmallString<1> Compressed;
- cantFail(zlib::compress(RawTable, Compressed));
+ if (llvm::zlib::isAvailable()) {
+ llvm::SmallString<1> Compressed;
+ llvm::cantFail(llvm::zlib::compress(RawTable, Compressed));
write32(RawTable.size(), OS);
OS << Compressed;
} else {
@@ -178,7 +178,7 @@ public:
}
}
// Get the ID of an string, which must be interned. Table must be finalized.
- unsigned index(StringRef S) const {
+ unsigned index(llvm::StringRef S) const {
assert(!Sorted.empty() && "table not finalized");
assert(Index.count({S.data(), S.size()}) && "string not interned");
return Index.find({S.data(), S.size()})->second;
@@ -186,33 +186,33 @@ public:
};
struct StringTableIn {
- BumpPtrAllocator Arena;
- std::vector<StringRef> Strings;
+ llvm::BumpPtrAllocator Arena;
+ std::vector<llvm::StringRef> Strings;
};
-Expected<StringTableIn> readStringTable(StringRef Data) {
+llvm::Expected<StringTableIn> readStringTable(llvm::StringRef Data) {
Reader R(Data);
size_t UncompressedSize = R.consume32();
if (R.err())
return makeError("Truncated string table");
- StringRef Uncompressed;
- SmallString<1> UncompressedStorage;
+ llvm::StringRef Uncompressed;
+ llvm::SmallString<1> UncompressedStorage;
if (UncompressedSize == 0) // No compression
Uncompressed = R.rest();
else {
- if (Error E = llvm::zlib::uncompress(R.rest(), UncompressedStorage,
- UncompressedSize))
+ if (llvm::Error E = llvm::zlib::uncompress(R.rest(), UncompressedStorage,
+ UncompressedSize))
return std::move(E);
Uncompressed = UncompressedStorage;
}
StringTableIn Table;
- StringSaver Saver(Table.Arena);
+ llvm::StringSaver Saver(Table.Arena);
R = Reader(Uncompressed);
for (Reader R(Uncompressed); !R.eof();) {
auto Len = R.rest().find(0);
- if (Len == StringRef::npos)
+ if (Len == llvm::StringRef::npos)
return makeError("Bad string table: not null terminated");
Table.Strings.push_back(Saver.save(R.consume(Len)));
R.consume8();
@@ -229,7 +229,7 @@ Expected<StringTableIn> readStringTable(StringRef Data) {
// - most numbers encode as varint
void writeLocation(const SymbolLocation &Loc, const StringTableOut &Strings,
- raw_ostream &OS) {
+ llvm::raw_ostream &OS) {
writeVar(Strings.index(Loc.FileURI), OS);
for (const auto &Endpoint : {Loc.Start, Loc.End}) {
writeVar(Endpoint.line(), OS);
@@ -237,7 +237,8 @@ void writeLocation(const SymbolLocation &Loc, const StringTableOut &Strings,
}
}
-SymbolLocation readLocation(Reader &Data, ArrayRef<StringRef> Strings) {
+SymbolLocation readLocation(Reader &Data,
+ llvm::ArrayRef<llvm::StringRef> Strings) {
SymbolLocation Loc;
Loc.FileURI = Data.consumeString(Strings).data();
for (auto *Endpoint : {&Loc.Start, &Loc.End}) {
@@ -261,7 +262,8 @@ IncludeGraphNode readIncludeGraphNode(Reader &Data,
}
void writeIncludeGraphNode(const IncludeGraphNode &IGN,
- const StringTableOut &Strings, raw_ostream &OS) {
+ const StringTableOut &Strings,
+ llvm::raw_ostream &OS) {
OS.write(IGN.IsTU);
writeVar(Strings.index(IGN.URI), OS);
llvm::StringRef Hash(reinterpret_cast<const char *>(IGN.Digest.data()),
@@ -273,7 +275,7 @@ void writeIncludeGraphNode(const IncludeGraphNode &IGN,
}
void writeSymbol(const Symbol &Sym, const StringTableOut &Strings,
- raw_ostream &OS) {
+ llvm::raw_ostream &OS) {
OS << Sym.ID.raw(); // TODO: once we start writing xrefs and posting lists,
// symbol IDs should probably be in a string table.
OS.write(static_cast<uint8_t>(Sym.SymInfo.Kind));
@@ -300,7 +302,7 @@ void writeSymbol(const Symbol &Sym, const StringTableOut &Strings,
WriteInclude(Include);
}
-Symbol readSymbol(Reader &Data, ArrayRef<StringRef> Strings) {
+Symbol readSymbol(Reader &Data, llvm::ArrayRef<llvm::StringRef> Strings) {
Symbol Sym;
Sym.ID = Data.consumeID();
Sym.SymInfo.Kind = static_cast<index::SymbolKind>(Data.consume8());
@@ -332,8 +334,8 @@ Symbol readSymbol(Reader &Data, ArrayRef<StringRef> Strings) {
// - Ref[NumRefs]
// Fields of Ref are encoded in turn, see implementation.
-void writeRefs(const SymbolID &ID, ArrayRef<Ref> Refs,
- const StringTableOut &Strings, raw_ostream &OS) {
+void writeRefs(const SymbolID &ID, llvm::ArrayRef<Ref> Refs,
+ const StringTableOut &Strings, llvm::raw_ostream &OS) {
OS << ID.raw();
writeVar(Refs.size(), OS);
for (const auto &Ref : Refs) {
@@ -342,8 +344,8 @@ void writeRefs(const SymbolID &ID, ArrayRef<Ref> Refs,
}
}
-std::pair<SymbolID, std::vector<Ref>> readRefs(Reader &Data,
- ArrayRef<StringRef> Strings) {
+std::pair<SymbolID, std::vector<Ref>>
+readRefs(Reader &Data, llvm::ArrayRef<llvm::StringRef> Strings) {
std::pair<SymbolID, std::vector<Ref>> Result;
Result.first = Data.consumeID();
Result.second.resize(Data.consumeVar());
@@ -368,17 +370,18 @@ std::pair<SymbolID, std::vector<Ref>> readRefs(Reader &Data,
// data. Later we may want to support some backward compatibility.
constexpr static uint32_t Version = 8;
-Expected<IndexFileIn> readRIFF(StringRef Data) {
+llvm::Expected<IndexFileIn> readRIFF(llvm::StringRef Data) {
auto RIFF = riff::readFile(Data);
if (!RIFF)
return RIFF.takeError();
if (RIFF->Type != riff::fourCC("CdIx"))
return makeError("wrong RIFF type");
- StringMap<StringRef> Chunks;
+ llvm::StringMap<llvm::StringRef> Chunks;
for (const auto &Chunk : RIFF->Chunks)
- Chunks.try_emplace(StringRef(Chunk.ID.data(), Chunk.ID.size()), Chunk.Data);
+ Chunks.try_emplace(llvm::StringRef(Chunk.ID.data(), Chunk.ID.size()),
+ Chunk.Data);
- for (StringRef RequiredChunk : {"meta", "stri"})
+ for (llvm::StringRef RequiredChunk : {"meta", "stri"})
if (!Chunks.count(RequiredChunk))
return makeError("missing required chunk " + RequiredChunk);
@@ -439,14 +442,14 @@ void visitStrings(IncludeGraphNode &IGN, const Callback &CB) {
CB(Include);
}
-void writeRIFF(const IndexFileOut &Data, raw_ostream &OS) {
+void writeRIFF(const IndexFileOut &Data, llvm::raw_ostream &OS) {
assert(Data.Symbols && "An index file without symbols makes no sense!");
riff::File RIFF;
RIFF.Type = riff::fourCC("CdIx");
- SmallString<4> Meta;
+ llvm::SmallString<4> Meta;
{
- raw_svector_ostream MetaOS(Meta);
+ llvm::raw_svector_ostream MetaOS(Meta);
write32(Version, MetaOS);
}
RIFF.Chunks.push_back({riff::fourCC("meta"), Meta});
@@ -455,13 +458,15 @@ void writeRIFF(const IndexFileOut &Data, raw_ostream &OS) {
std::vector<Symbol> Symbols;
for (const auto &Sym : *Data.Symbols) {
Symbols.emplace_back(Sym);
- visitStrings(Symbols.back(), [&](StringRef &S) { Strings.intern(S); });
+ visitStrings(Symbols.back(),
+ [&](llvm::StringRef &S) { Strings.intern(S); });
}
std::vector<IncludeGraphNode> Sources;
if (Data.Sources)
for (const auto &Source : *Data.Sources) {
Sources.push_back(Source.getValue());
- visitStrings(Sources.back(), [&](StringRef &S) { Strings.intern(S); });
+ visitStrings(Sources.back(),
+ [&](llvm::StringRef &S) { Strings.intern(S); });
}
std::vector<std::pair<SymbolID, std::vector<Ref>>> Refs;
@@ -469,7 +474,7 @@ void writeRIFF(const IndexFileOut &Data, raw_ostream &OS) {
for (const auto &Sym : *Data.Refs) {
Refs.emplace_back(Sym);
for (auto &Ref : Refs.back().second) {
- StringRef File = Ref.Location.FileURI;
+ llvm::StringRef File = Ref.Location.FileURI;
Strings.intern(File);
Ref.Location.FileURI = File.data();
}
@@ -478,14 +483,14 @@ void writeRIFF(const IndexFileOut &Data, raw_ostream &OS) {
std::string StringSection;
{
- raw_string_ostream StringOS(StringSection);
+ llvm::raw_string_ostream StringOS(StringSection);
Strings.finalize(StringOS);
}
RIFF.Chunks.push_back({riff::fourCC("stri"), StringSection});
std::string SymbolSection;
{
- raw_string_ostream SymbolOS(SymbolSection);
+ llvm::raw_string_ostream SymbolOS(SymbolSection);
for (const auto &Sym : Symbols)
writeSymbol(Sym, Strings, SymbolOS);
}
@@ -494,7 +499,7 @@ void writeRIFF(const IndexFileOut &Data, raw_ostream &OS) {
std::string RefsSection;
if (Data.Refs) {
{
- raw_string_ostream RefsOS(RefsSection);
+ llvm::raw_string_ostream RefsOS(RefsSection);
for (const auto &Sym : Refs)
writeRefs(Sym.first, Sym.second, Strings, RefsOS);
}
@@ -504,7 +509,7 @@ void writeRIFF(const IndexFileOut &Data, raw_ostream &OS) {
std::string SrcsSection;
{
{
- raw_string_ostream SrcsOS(SrcsSection);
+ llvm::raw_string_ostream SrcsOS(SrcsSection);
for (const auto &SF : Sources)
writeIncludeGraphNode(SF, Strings, SrcsOS);
}
@@ -517,10 +522,10 @@ void writeRIFF(const IndexFileOut &Data, raw_ostream &OS) {
} // namespace
// Defined in YAMLSerialization.cpp.
-void writeYAML(const IndexFileOut &, raw_ostream &);
-Expected<IndexFileIn> readYAML(StringRef);
+void writeYAML(const IndexFileOut &, llvm::raw_ostream &);
+llvm::Expected<IndexFileIn> readYAML(llvm::StringRef);
-raw_ostream &operator<<(raw_ostream &OS, const IndexFileOut &O) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const IndexFileOut &O) {
switch (O.Format) {
case IndexFileFormat::RIFF:
writeRIFF(O, OS);
@@ -532,22 +537,23 @@ raw_ostream &operator<<(raw_ostream &OS, const IndexFileOut &O) {
return OS;
}
-Expected<IndexFileIn> readIndexFile(StringRef Data) {
+llvm::Expected<IndexFileIn> readIndexFile(llvm::StringRef Data) {
if (Data.startswith("RIFF")) {
return readRIFF(Data);
} else if (auto YAMLContents = readYAML(Data)) {
return std::move(*YAMLContents);
} else {
return makeError("Not a RIFF file and failed to parse as YAML: " +
- toString(YAMLContents.takeError()));
+ llvm::toString(YAMLContents.takeError()));
}
}
-std::unique_ptr<SymbolIndex> loadIndex(StringRef SymbolFilename, bool UseDex) {
+std::unique_ptr<SymbolIndex> loadIndex(llvm::StringRef SymbolFilename,
+ bool UseDex) {
trace::Span OverallTracer("LoadIndex");
- auto Buffer = MemoryBuffer::getFile(SymbolFilename);
+ auto Buffer = llvm::MemoryBuffer::getFile(SymbolFilename);
if (!Buffer) {
- errs() << "Can't open " << SymbolFilename << "\n";
+ llvm::errs() << "Can't open " << SymbolFilename << "\n";
return nullptr;
}
@@ -561,7 +567,7 @@ std::unique_ptr<SymbolIndex> loadIndex(StringRef SymbolFilename, bool UseDex) {
if (I->Refs)
Refs = std::move(*I->Refs);
} else {
- errs() << "Bad Index: " << toString(I.takeError()) << "\n";
+ llvm::errs() << "Bad Index: " << llvm::toString(I.takeError()) << "\n";
return nullptr;
}
}
diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index 1e5478c74ae..cdc6aa5c01f 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -29,7 +29,6 @@
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -60,9 +59,9 @@ std::string toURI(const SourceManager &SM, llvm::StringRef Path,
}
// We don't perform is_absolute check in an else branch because makeAbsolute
// might return a relative path on some InMemoryFileSystems.
- if (!sys::path::is_absolute(AbsolutePath) && !Opts.FallbackDir.empty())
- sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath);
- sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
+ if (!llvm::sys::path::is_absolute(AbsolutePath) && !Opts.FallbackDir.empty())
+ llvm::sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath);
+ llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
return URI::create(AbsolutePath).toString();
}
@@ -102,7 +101,7 @@ bool isPrivateProtoDecl(const NamedDecl &ND) {
// will include OUTER_INNER and exclude some_enum_constant.
// FIXME: the heuristic relies on naming style (i.e. no underscore in
// user-defined names) and can be improved.
- return (ND.getKind() != Decl::EnumConstant) || any_of(Name, islower);
+ return (ND.getKind() != Decl::EnumConstant) || llvm::any_of(Name, islower);
}
// We only collect #include paths for symbols that are suitable for global code
@@ -130,9 +129,9 @@ bool shouldCollectIncludePath(index::SymbolKind Kind) {
/// Gets a canonical include (URI of the header or <header> or "header") for
/// header of \p Loc.
/// Returns None if fails to get include header for \p Loc.
-Optional<std::string> getIncludeHeader(StringRef QName, const SourceManager &SM,
- SourceLocation Loc,
- const SymbolCollector::Options &Opts) {
+llvm::Optional<std::string>
+getIncludeHeader(llvm::StringRef QName, const SourceManager &SM,
+ SourceLocation Loc, const SymbolCollector::Options &Opts) {
std::vector<std::string> Headers;
// Collect the #include stack.
while (true) {
@@ -148,7 +147,7 @@ Optional<std::string> getIncludeHeader(StringRef QName, const SourceManager &SM,
}
if (Headers.empty())
return None;
- StringRef Header = Headers[0];
+ llvm::StringRef Header = Headers[0];
if (Opts.Includes) {
Header = Opts.Includes->mapHeader(Headers, QName);
if (Header.startswith("<") || Header.startswith("\""))
@@ -186,11 +185,11 @@ bool shouldIndexFile(const SourceManager &SM, FileID FID,
}
// Return the symbol location of the token at \p TokLoc.
-Optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc,
- const SourceManager &SM,
- const SymbolCollector::Options &Opts,
- const clang::LangOptions &LangOpts,
- std::string &FileURIStorage) {
+llvm::Optional<SymbolLocation>
+getTokenLocation(SourceLocation TokLoc, const SourceManager &SM,
+ const SymbolCollector::Options &Opts,
+ const clang::LangOptions &LangOpts,
+ std::string &FileURIStorage) {
auto Path = SM.getFilename(TokLoc);
if (Path.empty())
return None;
@@ -299,7 +298,7 @@ bool SymbolCollector::shouldCollectSymbol(const NamedDecl &ND,
// Always return true to continue indexing.
bool SymbolCollector::handleDeclOccurence(
const Decl *D, index::SymbolRoleSet Roles,
- ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc,
+ llvm::ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc,
index::IndexDataConsumer::ASTNodeInfo ASTNode) {
assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
assert(CompletionAllocator && CompletionTUInfo);
@@ -461,8 +460,8 @@ void SymbolCollector::finish() {
}
const auto &SM = ASTCtx->getSourceManager();
- DenseMap<FileID, std::string> URICache;
- auto GetURI = [&](FileID FID) -> Optional<std::string> {
+ llvm::DenseMap<FileID, std::string> URICache;
+ auto GetURI = [&](FileID FID) -> llvm::Optional<std::string> {
auto Found = URICache.find(FID);
if (Found == URICache.end()) {
if (auto *FileEntry = SM.getFileEntryForID(FID)) {
diff --git a/clang-tools-extra/clangd/index/SymbolID.cpp b/clang-tools-extra/clangd/index/SymbolID.cpp
index 0ab74810a92..1fd427445f7 100644
--- a/clang-tools-extra/clangd/index/SymbolID.cpp
+++ b/clang-tools-extra/clangd/index/SymbolID.cpp
@@ -10,40 +10,42 @@
#include "SymbolID.h"
#include "llvm/Support/SHA1.h"
-using namespace llvm;
namespace clang {
namespace clangd {
-SymbolID::SymbolID(StringRef USR) {
- auto Hash = llvm::SHA1::hash(arrayRefFromStringRef(USR));
+SymbolID::SymbolID(llvm::StringRef USR) {
+ auto Hash = llvm::SHA1::hash(llvm::arrayRefFromStringRef(USR));
static_assert(sizeof(Hash) >= RawSize, "RawSize larger than SHA1");
memcpy(HashValue.data(), Hash.data(), RawSize);
}
llvm::StringRef SymbolID::raw() const {
- return StringRef(reinterpret_cast<const char *>(HashValue.data()), RawSize);
+ return llvm::StringRef(reinterpret_cast<const char *>(HashValue.data()),
+ RawSize);
}
-SymbolID SymbolID::fromRaw(StringRef Raw) {
+SymbolID SymbolID::fromRaw(llvm::StringRef Raw) {
SymbolID ID;
assert(Raw.size() == RawSize);
memcpy(ID.HashValue.data(), Raw.data(), RawSize);
return ID;
}
-std::string SymbolID::str() const { return toHex(raw()); }
+std::string SymbolID::str() const { return llvm::toHex(raw()); }
-Expected<SymbolID> SymbolID::fromStr(StringRef Str) {
+llvm::Expected<SymbolID> SymbolID::fromStr(llvm::StringRef Str) {
if (Str.size() != RawSize * 2)
- return createStringError(inconvertibleErrorCode(), "Bad ID length");
+ return llvm::createStringError(llvm::inconvertibleErrorCode(),
+ "Bad ID length");
for (char C : Str)
- if (!isHexDigit(C))
- return createStringError(inconvertibleErrorCode(), "Bad hex ID");
- return fromRaw(fromHex(Str));
+ if (!llvm::isHexDigit(C))
+ return llvm::createStringError(llvm::inconvertibleErrorCode(),
+ "Bad hex ID");
+ return fromRaw(llvm::fromHex(Str));
}
-raw_ostream &operator<<(raw_ostream &OS, const SymbolID &ID) {
- return OS << toHex(ID.raw());
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const SymbolID &ID) {
+ return OS << llvm::toHex(ID.raw());
}
llvm::hash_code hash_value(const SymbolID &ID) {
diff --git a/clang-tools-extra/clangd/index/YAMLSerialization.cpp b/clang-tools-extra/clangd/index/YAMLSerialization.cpp
index d3ffdddcaa4..27ed299e395 100644
--- a/clang-tools-extra/clangd/index/YAMLSerialization.cpp
+++ b/clang-tools-extra/clangd/index/YAMLSerialization.cpp
@@ -28,8 +28,6 @@
#include "llvm/Support/raw_ostream.h"
#include <cstdint>
-using namespace llvm;
-
LLVM_YAML_IS_SEQUENCE_VECTOR(clang::clangd::Symbol::IncludeHeaderWithReferences)
LLVM_YAML_IS_SEQUENCE_VECTOR(clang::clangd::Ref)
@@ -38,8 +36,8 @@ using RefBundle =
std::pair<clang::clangd::SymbolID, std::vector<clang::clangd::Ref>>;
// This is a pale imitation of std::variant<Symbol, RefBundle>
struct VariantEntry {
- Optional<clang::clangd::Symbol> Symbol;
- Optional<RefBundle> Refs;
+ llvm::Optional<clang::clangd::Symbol> Symbol;
+ llvm::Optional<RefBundle> Refs;
};
// A class helps YAML to serialize the 32-bit encoded position (Line&Column),
// as YAMLIO can't directly map bitfields.
@@ -66,14 +64,14 @@ using clang::index::SymbolLanguage;
struct NormalizedSymbolID {
NormalizedSymbolID(IO &) {}
NormalizedSymbolID(IO &, const SymbolID &ID) {
- raw_string_ostream OS(HexString);
+ llvm::raw_string_ostream OS(HexString);
OS << ID;
}
SymbolID denormalize(IO &I) {
auto ID = SymbolID::fromStr(HexString);
if (!ID) {
- I.setError(toString(ID.takeError()));
+ I.setError(llvm::toString(ID.takeError()));
return SymbolID();
}
return *ID;
@@ -294,8 +292,8 @@ template <> struct MappingTraits<VariantEntry> {
namespace clang {
namespace clangd {
-void writeYAML(const IndexFileOut &O, raw_ostream &OS) {
- yaml::Output Yout(OS);
+void writeYAML(const IndexFileOut &O, llvm::raw_ostream &OS) {
+ llvm::yaml::Output Yout(OS);
for (const auto &Sym : *O.Symbols) {
VariantEntry Entry;
Entry.Symbol = Sym;
@@ -309,17 +307,18 @@ void writeYAML(const IndexFileOut &O, raw_ostream &OS) {
}
}
-Expected<IndexFileIn> readYAML(StringRef Data) {
+llvm::Expected<IndexFileIn> readYAML(llvm::StringRef Data) {
SymbolSlab::Builder Symbols;
RefSlab::Builder Refs;
- BumpPtrAllocator Arena; // store the underlying data of Position::FileURI.
- UniqueStringSaver Strings(Arena);
- yaml::Input Yin(Data, &Strings);
+ llvm::BumpPtrAllocator
+ Arena; // store the underlying data of Position::FileURI.
+ llvm::UniqueStringSaver Strings(Arena);
+ llvm::yaml::Input Yin(Data, &Strings);
do {
VariantEntry Variant;
Yin >> Variant;
if (Yin.error())
- return errorCodeToError(Yin.error());
+ return llvm::errorCodeToError(Yin.error());
if (Variant.Symbol)
Symbols.insert(*Variant.Symbol);
if (Variant.Refs)
@@ -336,20 +335,20 @@ Expected<IndexFileIn> readYAML(StringRef Data) {
std::string toYAML(const Symbol &S) {
std::string Buf;
{
- raw_string_ostream OS(Buf);
- yaml::Output Yout(OS);
+ llvm::raw_string_ostream OS(Buf);
+ llvm::yaml::Output Yout(OS);
Symbol Sym = S; // copy: Yout<< requires mutability.
Yout << Sym;
}
return Buf;
}
-std::string toYAML(const std::pair<SymbolID, ArrayRef<Ref>> &Data) {
+std::string toYAML(const std::pair<SymbolID, llvm::ArrayRef<Ref>> &Data) {
RefBundle Refs = {Data.first, Data.second};
std::string Buf;
{
- raw_string_ostream OS(Buf);
- yaml::Output Yout(OS);
+ llvm::raw_string_ostream OS(Buf);
+ llvm::yaml::Output Yout(OS);
Yout << Refs;
}
return Buf;
diff --git a/clang-tools-extra/clangd/index/dex/Dex.cpp b/clang-tools-extra/clangd/index/dex/Dex.cpp
index 8d64e1b48c9..157d4668856 100644
--- a/clang-tools-extra/clangd/index/dex/Dex.cpp
+++ b/clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -20,7 +20,6 @@
#include <algorithm>
#include <queue>
-using namespace llvm;
namespace clang {
namespace clangd {
namespace dex {
@@ -50,7 +49,7 @@ std::vector<Token> generateSearchTokens(const Symbol &Sym) {
std::vector<Token> Result = generateIdentifierTrigrams(Sym.Name);
Result.emplace_back(Token::Kind::Scope, Sym.Scope);
// Skip token generation for symbols with unknown declaration location.
- if (!StringRef(Sym.CanonicalDeclaration.FileURI).empty())
+ if (!llvm::StringRef(Sym.CanonicalDeclaration.FileURI).empty())
for (const auto &ProximityURI :
generateProximityURIs(Sym.CanonicalDeclaration.FileURI))
Result.emplace_back(Token::Kind::ProximityURI, ProximityURI);
@@ -60,14 +59,14 @@ std::vector<Token> generateSearchTokens(const Symbol &Sym) {
}
// Constructs BOOST iterators for Path Proximities.
-std::unique_ptr<Iterator>
-createFileProximityIterator(ArrayRef<std::string> ProximityPaths,
- const DenseMap<Token, PostingList> &InvertedIndex,
- const Corpus &Corpus) {
+std::unique_ptr<Iterator> createFileProximityIterator(
+ llvm::ArrayRef<std::string> ProximityPaths,
+ const llvm::DenseMap<Token, PostingList> &InvertedIndex,
+ const Corpus &Corpus) {
std::vector<std::unique_ptr<Iterator>> BoostingIterators;
// Deduplicate parent URIs extracted from the ProximityPaths.
- StringSet<> ParentURIs;
- StringMap<SourceParams> Sources;
+ llvm::StringSet<> ParentURIs;
+ llvm::StringMap<SourceParams> Sources;
for (const auto &Path : ProximityPaths) {
Sources[Path] = SourceParams();
auto PathURI = URI::create(Path);
@@ -124,7 +123,7 @@ void Dex::buildIndex() {
}
// Populate TempInvertedIndex with lists for index symbols.
- DenseMap<Token, std::vector<DocID>> TempInvertedIndex;
+ llvm::DenseMap<Token, std::vector<DocID>> TempInvertedIndex;
for (DocID SymbolRank = 0; SymbolRank < Symbols.size(); ++SymbolRank) {
const auto *Sym = Symbols[SymbolRank];
for (const auto &Token : generateSearchTokens(*Sym))
@@ -147,7 +146,7 @@ std::unique_ptr<Iterator> Dex::iterator(const Token &Tok) const {
/// while applying Callback to each symbol in the order of decreasing quality
/// of the matched symbols.
bool Dex::fuzzyFind(const FuzzyFindRequest &Req,
- function_ref<void(const Symbol &)> Callback) const {
+ llvm::function_ref<void(const Symbol &)> Callback) const {
assert(!StringRef(Req.Query).contains("::") &&
"There must be no :: in query.");
trace::Span Tracer("Dex fuzzyFind");
@@ -190,7 +189,7 @@ bool Dex::fuzzyFind(const FuzzyFindRequest &Req,
// FIXME(kbobyrev): Tune this ratio.
if (Req.Limit)
Root = Corpus.limit(move(Root), *Req.Limit * 100);
- SPAN_ATTACH(Tracer, "query", to_string(*Root));
+ SPAN_ATTACH(Tracer, "query", llvm::to_string(*Root));
vlog("Dex query tree: {0}", *Root);
using IDAndScore = std::pair<DocID, float>;
@@ -204,7 +203,7 @@ bool Dex::fuzzyFind(const FuzzyFindRequest &Req,
for (const auto &IDAndScore : IDAndScores) {
const DocID SymbolDocID = IDAndScore.first;
const auto *Sym = Symbols[SymbolDocID];
- const Optional<float> Score = Filter.match(Sym->Name);
+ const llvm::Optional<float> Score = Filter.match(Sym->Name);
if (!Score)
continue;
// Combine Fuzzy Matching score, precomputed symbol quality and boosting
@@ -225,7 +224,7 @@ bool Dex::fuzzyFind(const FuzzyFindRequest &Req,
}
void Dex::lookup(const LookupRequest &Req,
- function_ref<void(const Symbol &)> Callback) const {
+ llvm::function_ref<void(const Symbol &)> Callback) const {
trace::Span Tracer("Dex lookup");
for (const auto &ID : Req.IDs) {
auto I = LookupTable.find(ID);
@@ -235,7 +234,7 @@ void Dex::lookup(const LookupRequest &Req,
}
void Dex::refs(const RefsRequest &Req,
- function_ref<void(const Ref &)> Callback) const {
+ llvm::function_ref<void(const Ref &)> Callback) const {
trace::Span Tracer("Dex refs");
for (const auto &ID : Req.IDs)
for (const auto &Ref : Refs.lookup(ID))
@@ -254,13 +253,13 @@ size_t Dex::estimateMemoryUsage() const {
return Bytes + BackingDataSize;
}
-std::vector<std::string> generateProximityURIs(StringRef URIPath) {
+std::vector<std::string> generateProximityURIs(llvm::StringRef URIPath) {
std::vector<std::string> Result;
auto ParsedURI = URI::parse(URIPath);
assert(ParsedURI &&
"Non-empty argument of generateProximityURIs() should be a valid "
"URI.");
- StringRef Body = ParsedURI->body();
+ llvm::StringRef Body = ParsedURI->body();
// FIXME(kbobyrev): Currently, this is a heuristic which defines the maximum
// size of resulting vector. Some projects might want to have higher limit if
// the file hierarchy is deeper. For the generic case, it would be useful to
@@ -273,7 +272,7 @@ std::vector<std::string> generateProximityURIs(StringRef URIPath) {
while (!Body.empty() && --Limit > 0) {
// FIXME(kbobyrev): Parsing and encoding path to URIs is not necessary and
// could be optimized.
- Body = sys::path::parent_path(Body, sys::path::Style::posix);
+ Body = llvm::sys::path::parent_path(Body, llvm::sys::path::Style::posix);
URI TokenURI(ParsedURI->scheme(), ParsedURI->authority(), Body);
if (!Body.empty())
Result.emplace_back(TokenURI.toString());
diff --git a/clang-tools-extra/clangd/index/dex/Iterator.cpp b/clang-tools-extra/clangd/index/dex/Iterator.cpp
index 9e62c155ee7..0b132b94c43 100644
--- a/clang-tools-extra/clangd/index/dex/Iterator.cpp
+++ b/clang-tools-extra/clangd/index/dex/Iterator.cpp
@@ -13,7 +13,6 @@
#include <cassert>
#include <numeric>
-using namespace llvm;
namespace clang {
namespace clangd {
namespace dex {
@@ -77,7 +76,7 @@ public:
}
private:
- raw_ostream &dump(raw_ostream &OS) const override {
+ llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
OS << "(& ";
auto Separator = "";
for (const auto &Child : Children) {
@@ -198,7 +197,7 @@ public:
}
private:
- raw_ostream &dump(raw_ostream &OS) const override {
+ llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
OS << "(| ";
auto Separator = "";
for (const auto &Child : Children) {
@@ -246,7 +245,9 @@ public:
size_t estimateSize() const override { return Size; }
private:
- raw_ostream &dump(raw_ostream &OS) const override { return OS << "true"; }
+ llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+ return OS << "true";
+ }
DocID Index = 0;
/// Size of the underlying virtual PostingList.
@@ -271,7 +272,9 @@ public:
size_t estimateSize() const override { return 0; }
private:
- raw_ostream &dump(raw_ostream &OS) const override { return OS << "false"; }
+ llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+ return OS << "false";
+ }
};
/// Boost iterator is a wrapper around its child which multiplies scores of
@@ -294,7 +297,7 @@ public:
size_t estimateSize() const override { return Child->estimateSize(); }
private:
- raw_ostream &dump(raw_ostream &OS) const override {
+ llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
return OS << "(* " << Factor << ' ' << *Child << ')';
}
@@ -334,7 +337,7 @@ public:
}
private:
- raw_ostream &dump(raw_ostream &OS) const override {
+ llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
return OS << "(LIMIT " << Limit << " " << *Child << ')';
}
diff --git a/clang-tools-extra/clangd/index/dex/PostingList.cpp b/clang-tools-extra/clangd/index/dex/PostingList.cpp
index a0c8afdf08a..eb2e4757d43 100644
--- a/clang-tools-extra/clangd/index/dex/PostingList.cpp
+++ b/clang-tools-extra/clangd/index/dex/PostingList.cpp
@@ -13,7 +13,6 @@
#include "llvm/Support/Error.h"
#include "llvm/Support/MathExtras.h"
-using namespace llvm;
namespace clang {
namespace clangd {
namespace dex {
@@ -24,7 +23,7 @@ namespace {
/// them on-the-fly when the contents of chunk are to be seen.
class ChunkIterator : public Iterator {
public:
- explicit ChunkIterator(const Token *Tok, ArrayRef<Chunk> Chunks)
+ explicit ChunkIterator(const Token *Tok, llvm::ArrayRef<Chunk> Chunks)
: Tok(Tok), Chunks(Chunks), CurrentChunk(Chunks.begin()) {
if (!Chunks.empty()) {
DecompressedChunk = CurrentChunk->decompress();
@@ -71,7 +70,7 @@ public:
}
private:
- raw_ostream &dump(raw_ostream &OS) const override {
+ llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
if (Tok != nullptr)
return OS << *Tok;
OS << '[';
@@ -113,13 +112,13 @@ private:
}
const Token *Tok;
- ArrayRef<Chunk> Chunks;
+ llvm::ArrayRef<Chunk> Chunks;
/// Iterator over chunks.
/// If CurrentChunk is valid, then DecompressedChunk is
/// CurrentChunk->decompress() and CurrentID is a valid (non-end) iterator
/// into it.
decltype(Chunks)::const_iterator CurrentChunk;
- SmallVector<DocID, Chunk::PayloadSize + 1> DecompressedChunk;
+ llvm::SmallVector<DocID, Chunk::PayloadSize + 1> DecompressedChunk;
/// Iterator over DecompressedChunk.
decltype(DecompressedChunk)::iterator CurrentID;
@@ -130,11 +129,11 @@ static constexpr size_t BitsPerEncodingByte = 7;
/// Writes a variable length DocID into the buffer and updates the buffer size.
/// If it doesn't fit, returns false and doesn't write to the buffer.
-bool encodeVByte(DocID Delta, MutableArrayRef<uint8_t> &Payload) {
+bool encodeVByte(DocID Delta, llvm::MutableArrayRef<uint8_t> &Payload) {
assert(Delta != 0 && "0 is not a valid PostingList delta.");
// Calculate number of bytes Delta encoding would take by examining the
// meaningful bits.
- unsigned Width = 1 + findLastSet(Delta) / BitsPerEncodingByte;
+ unsigned Width = 1 + llvm::findLastSet(Delta) / BitsPerEncodingByte;
if (Width > Payload.size())
return false;
@@ -166,12 +165,12 @@ bool encodeVByte(DocID Delta, MutableArrayRef<uint8_t> &Payload) {
/// DocIDs 42 47 7000
/// gaps 5 6958
/// Encoding (raw number) 00000101 10110110 00101110
-std::vector<Chunk> encodeStream(ArrayRef<DocID> Documents) {
+std::vector<Chunk> encodeStream(llvm::ArrayRef<DocID> Documents) {
assert(!Documents.empty() && "Can't encode empty sequence.");
std::vector<Chunk> Result;
Result.emplace_back();
DocID Last = Result.back().Head = Documents.front();
- MutableArrayRef<uint8_t> RemainingPayload = Result.back().Payload;
+ llvm::MutableArrayRef<uint8_t> RemainingPayload = Result.back().Payload;
for (DocID Doc : Documents.drop_front()) {
if (!encodeVByte(Doc - Last, RemainingPayload)) { // didn't fit, flush chunk
Result.emplace_back();
@@ -185,7 +184,7 @@ std::vector<Chunk> encodeStream(ArrayRef<DocID> Documents) {
/// Reads variable length DocID from the buffer and updates the buffer size. If
/// the stream is terminated, return None.
-Optional<DocID> readVByte(ArrayRef<uint8_t> &Bytes) {
+llvm::Optional<DocID> readVByte(llvm::ArrayRef<uint8_t> &Bytes) {
if (Bytes.front() == 0 || Bytes.empty())
return None;
DocID Result = 0;
@@ -203,9 +202,9 @@ Optional<DocID> readVByte(ArrayRef<uint8_t> &Bytes) {
} // namespace
-SmallVector<DocID, Chunk::PayloadSize + 1> Chunk::decompress() const {
- SmallVector<DocID, Chunk::PayloadSize + 1> Result{Head};
- ArrayRef<uint8_t> Bytes(Payload);
+llvm::SmallVector<DocID, Chunk::PayloadSize + 1> Chunk::decompress() const {
+ llvm::SmallVector<DocID, Chunk::PayloadSize + 1> Result{Head};
+ llvm::ArrayRef<uint8_t> Bytes(Payload);
DocID Delta;
for (DocID Current = Head; !Bytes.empty(); Current += Delta) {
auto MaybeDelta = readVByte(Bytes);
@@ -214,10 +213,10 @@ SmallVector<DocID, Chunk::PayloadSize + 1> Chunk::decompress() const {
Delta = *MaybeDelta;
Result.push_back(Current + Delta);
}
- return SmallVector<DocID, Chunk::PayloadSize + 1>{Result};
+ return llvm::SmallVector<DocID, Chunk::PayloadSize + 1>{Result};
}
-PostingList::PostingList(ArrayRef<DocID> Documents)
+PostingList::PostingList(llvm::ArrayRef<DocID> Documents)
: Chunks(encodeStream(Documents)) {}
std::unique_ptr<Iterator> PostingList::iterator(const Token *Tok) const {
diff --git a/clang-tools-extra/clangd/index/dex/Trigram.cpp b/clang-tools-extra/clangd/index/dex/Trigram.cpp
index 7779e8b8ba8..2ba0ad18cc7 100644
--- a/clang-tools-extra/clangd/index/dex/Trigram.cpp
+++ b/clang-tools-extra/clangd/index/dex/Trigram.cpp
@@ -17,16 +17,15 @@
#include <queue>
#include <string>
-using namespace llvm;
namespace clang {
namespace clangd {
namespace dex {
-std::vector<Token> generateIdentifierTrigrams(StringRef Identifier) {
+std::vector<Token> generateIdentifierTrigrams(llvm::StringRef Identifier) {
// Apply fuzzy matching text segmentation.
std::vector<CharRole> Roles(Identifier.size());
calculateRoles(Identifier,
- makeMutableArrayRef(Roles.data(), Identifier.size()));
+ llvm::makeMutableArrayRef(Roles.data(), Identifier.size()));
std::string LowercaseIdentifier = Identifier.lower();
@@ -48,7 +47,7 @@ std::vector<Token> generateIdentifierTrigrams(StringRef Identifier) {
}
}
- DenseSet<Token> UniqueTrigrams;
+ llvm::DenseSet<Token> UniqueTrigrams;
auto Add = [&](std::string Chars) {
UniqueTrigrams.insert(Token(Token::Kind::Trigram, Chars));
@@ -85,7 +84,7 @@ std::vector<Token> generateIdentifierTrigrams(StringRef Identifier) {
return {UniqueTrigrams.begin(), UniqueTrigrams.end()};
}
-std::vector<Token> generateQueryTrigrams(StringRef Query) {
+std::vector<Token> generateQueryTrigrams(llvm::StringRef Query) {
if (Query.empty())
return {};
std::string LowercaseQuery = Query.lower();
@@ -94,9 +93,9 @@ std::vector<Token> generateQueryTrigrams(StringRef Query) {
// Apply fuzzy matching text segmentation.
std::vector<CharRole> Roles(Query.size());
- calculateRoles(Query, makeMutableArrayRef(Roles.data(), Query.size()));
+ calculateRoles(Query, llvm::makeMutableArrayRef(Roles.data(), Query.size()));
- DenseSet<Token> UniqueTrigrams;
+ llvm::DenseSet<Token> UniqueTrigrams;
std::string Chars;
for (unsigned I = 0; I < Query.size(); ++I) {
if (Roles[I] != Head && Roles[I] != Tail)
diff --git a/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp b/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
index 795173c74ad..5a0b6d97122 100644
--- a/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
+++ b/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
@@ -22,14 +22,13 @@
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Signals.h"
-using namespace llvm;
-using namespace clang;
-using namespace clangd;
-
+namespace clang {
+namespace clangd {
namespace {
-cl::opt<std::string> IndexPath("index-path", cl::desc("Path to the index"),
- cl::Positional, cl::Required);
+llvm::cl::opt<std::string> IndexPath("index-path",
+ llvm::cl::desc("Path to the index"),
+ llvm::cl::Positional, llvm::cl::Required);
static const std::string Overview = R"(
This is an **experimental** interactive tool to process user-provided search
@@ -40,16 +39,16 @@ and manually construct non-trivial test cases.
Type use "help" request to get information about the details.
)";
-void reportTime(StringRef Name, function_ref<void()> F) {
+void reportTime(llvm::StringRef Name, llvm::function_ref<void()> F) {
const auto TimerStart = std::chrono::high_resolution_clock::now();
F();
const auto TimerStop = std::chrono::high_resolution_clock::now();
const auto Duration = std::chrono::duration_cast<std::chrono::milliseconds>(
TimerStop - TimerStart);
- outs() << formatv("{0} took {1:ms+n}.\n", Name, Duration);
+ llvm::outs() << llvm::formatv("{0} took {1:ms+n}.\n", Name, Duration);
}
-std::vector<SymbolID> getSymbolIDsFromIndex(StringRef QualifiedName,
+std::vector<SymbolID> getSymbolIDsFromIndex(llvm::StringRef QualifiedName,
const SymbolIndex *Index) {
FuzzyFindRequest Request;
// Remove leading "::" qualifier as FuzzyFind doesn't need leading "::"
@@ -77,9 +76,9 @@ std::vector<SymbolID> getSymbolIDsFromIndex(StringRef QualifiedName,
// Creating a Command populates parser options, parseAndRun() resets them.
class Command {
// By resetting the parser options, we lost the standard -help flag.
- cl::opt<bool, false, cl::parser<bool>> Help{
- "help", cl::desc("Display available options"), cl::ValueDisallowed,
- cl::cat(cl::GeneralCategory)};
+ llvm::cl::opt<bool, false, llvm::cl::parser<bool>> Help{
+ "help", llvm::cl::desc("Display available options"),
+ llvm::cl::ValueDisallowed, llvm::cl::cat(llvm::cl::GeneralCategory)};
virtual void run() = 0;
protected:
@@ -87,24 +86,25 @@ protected:
public:
virtual ~Command() = default;
- virtual void parseAndRun(ArrayRef<const char *> Argv, const char *Overview,
- const SymbolIndex &Index) {
+ virtual void parseAndRun(llvm::ArrayRef<const char *> Argv,
+ const char *Overview, const SymbolIndex &Index) {
std::string ParseErrs;
- raw_string_ostream OS(ParseErrs);
- bool Ok =
- cl::ParseCommandLineOptions(Argv.size(), Argv.data(), Overview, &OS);
+ llvm::raw_string_ostream OS(ParseErrs);
+ bool Ok = llvm::cl::ParseCommandLineOptions(Argv.size(), Argv.data(),
+ Overview, &OS);
if (Help.getNumOccurrences() > 0) {
// Avoid printing parse errors in this case.
// (Well, in theory. A bunch get printed to llvm::errs() regardless!)
- cl::PrintHelpMessage();
+ llvm::cl::PrintHelpMessage();
} else {
- outs() << OS.str();
+ llvm::outs() << OS.str();
if (Ok) {
this->Index = &Index;
reportTime(Argv[0], [&] { run(); });
}
}
- cl::ResetCommandLineParser(); // must do this before opts are destroyed.
+ llvm::cl::ResetCommandLineParser(); // must do this before opts are
+ // destroyed.
}
};
@@ -118,20 +118,20 @@ public:
// * print out tokens with least dense posting lists
class FuzzyFind : public Command {
- cl::opt<std::string> Query{
+ llvm::cl::opt<std::string> Query{
"query",
- cl::Positional,
- cl::Required,
- cl::desc("Query string to be fuzzy-matched"),
+ llvm::cl::Positional,
+ llvm::cl::Required,
+ llvm::cl::desc("Query string to be fuzzy-matched"),
};
- cl::opt<std::string> Scopes{
+ llvm::cl::opt<std::string> Scopes{
"scopes",
- cl::desc("Allowed symbol scopes (comma-separated list)"),
+ llvm::cl::desc("Allowed symbol scopes (comma-separated list)"),
};
- cl::opt<unsigned> Limit{
+ llvm::cl::opt<unsigned> Limit{
"limit",
- cl::init(10),
- cl::desc("Max results to display"),
+ llvm::cl::init(10),
+ llvm::cl::desc("Max results to display"),
};
void run() override {
@@ -139,42 +139,45 @@ class FuzzyFind : public Command {
Request.Limit = Limit;
Request.Query = Query;
if (Scopes.getNumOccurrences() > 0) {
- SmallVector<StringRef, 8> Scopes;
- StringRef(this->Scopes).split(Scopes, ',');
+ llvm::SmallVector<llvm::StringRef, 8> Scopes;
+ llvm::StringRef(this->Scopes).split(Scopes, ',');
Request.Scopes = {Scopes.begin(), Scopes.end()};
}
Request.AnyScope = Request.Scopes.empty();
// FIXME(kbobyrev): Print symbol final scores to see the distribution.
static const auto OutputFormat = "{0,-4} | {1,-40} | {2,-25}\n";
- outs() << formatv(OutputFormat, "Rank", "Symbol ID", "Symbol Name");
+ llvm::outs() << llvm::formatv(OutputFormat, "Rank", "Symbol ID",
+ "Symbol Name");
size_t Rank = 0;
Index->fuzzyFind(Request, [&](const Symbol &Sym) {
- outs() << formatv(OutputFormat, Rank++, Sym.ID.str(),
- Sym.Scope + Sym.Name);
+ llvm::outs() << llvm::formatv(OutputFormat, Rank++, Sym.ID.str(),
+ Sym.Scope + Sym.Name);
});
}
};
class Lookup : public Command {
- cl::opt<std::string> ID{
+ llvm::cl::opt<std::string> ID{
"id",
- cl::Positional,
- cl::desc("Symbol ID to look up (hex)"),
+ llvm::cl::Positional,
+ llvm::cl::desc("Symbol ID to look up (hex)"),
};
- cl::opt<std::string> Name{
- "name", cl::desc("Qualified name to look up."),
+ llvm::cl::opt<std::string> Name{
+ "name",
+ llvm::cl::desc("Qualified name to look up."),
};
void run() override {
if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {
- outs() << "Missing required argument: please provide id or -name.\n";
+ llvm::outs()
+ << "Missing required argument: please provide id or -name.\n";
return;
}
std::vector<SymbolID> IDs;
if (ID.getNumOccurrences()) {
auto SID = SymbolID::fromStr(ID);
if (!SID) {
- outs() << toString(SID.takeError()) << "\n";
+ llvm::outs() << llvm::toString(SID.takeError()) << "\n";
return;
}
IDs.push_back(*SID);
@@ -187,60 +190,65 @@ class Lookup : public Command {
bool FoundSymbol = false;
Index->lookup(Request, [&](const Symbol &Sym) {
FoundSymbol = true;
- outs() << toYAML(Sym);
+ llvm::outs() << toYAML(Sym);
});
if (!FoundSymbol)
- outs() << "not found\n";
+ llvm::outs() << "not found\n";
}
};
class Refs : public Command {
- cl::opt<std::string> ID{
- "id", cl::Positional,
- cl::desc("Symbol ID of the symbol being queried (hex)."),
+ llvm::cl::opt<std::string> ID{
+ "id",
+ llvm::cl::Positional,
+ llvm::cl::desc("Symbol ID of the symbol being queried (hex)."),
};
- cl::opt<std::string> Name{
- "name", cl::desc("Qualified name of the symbol being queried."),
+ llvm::cl::opt<std::string> Name{
+ "name",
+ llvm::cl::desc("Qualified name of the symbol being queried."),
};
- cl::opt<std::string> Filter{
- "filter", cl::init(".*"),
- cl::desc(
+ llvm::cl::opt<std::string> Filter{
+ "filter",
+ llvm::cl::init(".*"),
+ llvm::cl::desc(
"Print all results from files matching this regular expression."),
};
void run() override {
if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {
- outs() << "Missing required argument: please provide id or -name.\n";
+ llvm::outs()
+ << "Missing required argument: please provide id or -name.\n";
return;
}
std::vector<SymbolID> IDs;
if (ID.getNumOccurrences()) {
auto SID = SymbolID::fromStr(ID);
if (!SID) {
- outs() << toString(SID.takeError()) << "\n";
+ llvm::outs() << llvm::toString(SID.takeError()) << "\n";
return;
}
IDs.push_back(*SID);
} else {
IDs = getSymbolIDsFromIndex(Name, Index);
if (IDs.size() > 1) {
- outs() << formatv("The name {0} is ambiguous, found {1} different "
- "symbols. Please use id flag to disambiguate.\n",
- Name, IDs.size());
+ llvm::outs() << llvm::formatv(
+ "The name {0} is ambiguous, found {1} different "
+ "symbols. Please use id flag to disambiguate.\n",
+ Name, IDs.size());
return;
}
}
RefsRequest RefRequest;
RefRequest.IDs.insert(IDs.begin(), IDs.end());
- Regex RegexFilter(Filter);
+ llvm::Regex RegexFilter(Filter);
Index->refs(RefRequest, [&RegexFilter](const Ref &R) {
auto U = URI::parse(R.Location.FileURI);
if (!U) {
- outs() << U.takeError();
+ llvm::outs() << U.takeError();
return;
}
if (RegexFilter.match(U->body()))
- outs() << R << "\n";
+ llvm::outs() << R << "\n";
});
}
};
@@ -257,16 +265,20 @@ struct {
llvm::make_unique<Refs>},
};
-std::unique_ptr<SymbolIndex> openIndex(StringRef Index) {
+std::unique_ptr<SymbolIndex> openIndex(llvm::StringRef Index) {
return loadIndex(Index, /*UseDex=*/true);
}
} // namespace
+} // namespace clangd
+} // namespace clang
int main(int argc, const char *argv[]) {
- cl::ParseCommandLineOptions(argc, argv, Overview);
- cl::ResetCommandLineParser(); // We reuse it for REPL commands.
- sys::PrintStackTraceOnErrorSignal(argv[0]);
+ using namespace clang::clangd;
+
+ llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
+ llvm::cl::ResetCommandLineParser(); // We reuse it for REPL commands.
+ llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
std::unique_ptr<SymbolIndex> Index;
reportTime("Dex build", [&]() {
@@ -274,28 +286,29 @@ int main(int argc, const char *argv[]) {
});
if (!Index) {
- outs() << "Failed to open the index.\n";
+ llvm::outs() << "Failed to open the index.\n";
return -1;
}
- LineEditor LE("dexp");
+ llvm::LineEditor LE("dexp");
- while (Optional<std::string> Request = LE.readLine()) {
+ while (llvm::Optional<std::string> Request = LE.readLine()) {
// Split on spaces and add required null-termination.
std::replace(Request->begin(), Request->end(), ' ', '\0');
- SmallVector<StringRef, 8> Args;
- StringRef(*Request).split(Args, '\0', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
+ llvm::SmallVector<llvm::StringRef, 8> Args;
+ llvm::StringRef(*Request).split(Args, '\0', /*MaxSplit=*/-1,
+ /*KeepEmpty=*/false);
if (Args.empty())
continue;
if (Args.front() == "help") {
- outs() << "dexp - Index explorer\nCommands:\n";
+ llvm::outs() << "dexp - Index explorer\nCommands:\n";
for (const auto &C : CommandInfo)
- outs() << formatv("{0,16} - {1}\n", C.Name, C.Description);
- outs() << "Get detailed command help with e.g. `find -help`.\n";
+ llvm::outs() << llvm::formatv("{0,16} - {1}\n", C.Name, C.Description);
+ llvm::outs() << "Get detailed command help with e.g. `find -help`.\n";
continue;
}
- SmallVector<const char *, 8> FakeArgv;
- for (StringRef S : Args)
+ llvm::SmallVector<const char *, 8> FakeArgv;
+ for (llvm::StringRef S : Args)
FakeArgv.push_back(S.data()); // Terminated by separator or end of string.
bool Recognized = false;
@@ -307,7 +320,7 @@ int main(int argc, const char *argv[]) {
}
}
if (!Recognized)
- outs() << "Unknown command. Try 'help'.\n";
+ llvm::outs() << "Unknown command. Try 'help'.\n";
}
return 0;
diff --git a/clang-tools-extra/clangd/indexer/IndexerMain.cpp b/clang-tools-extra/clangd/indexer/IndexerMain.cpp
index 46716a959be..18e6304fe22 100644
--- a/clang-tools-extra/clangd/indexer/IndexerMain.cpp
+++ b/clang-tools-extra/clangd/indexer/IndexerMain.cpp
@@ -22,20 +22,17 @@
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Signals.h"
-using namespace llvm;
-using namespace clang::tooling;
-
namespace clang {
namespace clangd {
namespace {
-static cl::opt<IndexFileFormat>
- Format("format", cl::desc("Format of the index to be written"),
- cl::values(clEnumValN(IndexFileFormat::YAML, "yaml",
- "human-readable YAML format"),
- clEnumValN(IndexFileFormat::RIFF, "binary",
- "binary RIFF format")),
- cl::init(IndexFileFormat::RIFF));
+static llvm::cl::opt<IndexFileFormat>
+ Format("format", llvm::cl::desc("Format of the index to be written"),
+ llvm::cl::values(clEnumValN(IndexFileFormat::YAML, "yaml",
+ "human-readable YAML format"),
+ clEnumValN(IndexFileFormat::RIFF, "binary",
+ "binary RIFF format")),
+ llvm::cl::init(IndexFileFormat::RIFF));
class IndexActionFactory : public tooling::FrontendActionFactory {
public:
@@ -86,7 +83,7 @@ private:
} // namespace clang
int main(int argc, const char **argv) {
- sys::PrintStackTraceOnErrorSignal(argv[0]);
+ llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
const char *Overview = R"(
Creates an index of symbol information etc in a whole project.
@@ -103,10 +100,10 @@ int main(int argc, const char **argv) {
)";
auto Executor = clang::tooling::createExecutorFromCommandLineArgs(
- argc, argv, cl::GeneralCategory, Overview);
+ argc, argv, llvm::cl::GeneralCategory, Overview);
if (!Executor) {
- errs() << toString(Executor.takeError()) << "\n";
+ llvm::errs() << llvm::toString(Executor.takeError()) << "\n";
return 1;
}
@@ -115,12 +112,12 @@ int main(int argc, const char **argv) {
auto Err = Executor->get()->execute(
llvm::make_unique<clang::clangd::IndexActionFactory>(Data));
if (Err) {
- errs() << toString(std::move(Err)) << "\n";
+ llvm::errs() << llvm::toString(std::move(Err)) << "\n";
}
// Emit collected data.
clang::clangd::IndexFileOut Out(Data);
Out.Format = clang::clangd::Format;
- outs() << Out;
+ llvm::outs() << Out;
return 0;
}
diff --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index 3d94401f787..3d338aec8f0 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -25,176 +25,181 @@
#include <string>
#include <thread>
-using namespace llvm;
-using namespace clang;
-using namespace clang::clangd;
-
+namespace clang {
+namespace clangd {
// FIXME: remove this option when Dex is cheap enough.
-static cl::opt<bool> UseDex("use-dex-index",
- cl::desc("Use experimental Dex dynamic index."),
- cl::init(false), cl::Hidden);
+static llvm::cl::opt<bool>
+ UseDex("use-dex-index",
+ llvm::cl::desc("Use experimental Dex dynamic index."),
+ llvm::cl::init(false), llvm::cl::Hidden);
-static cl::opt<Path> CompileCommandsDir(
+static llvm::cl::opt<Path> CompileCommandsDir(
"compile-commands-dir",
- cl::desc("Specify a path to look for compile_commands.json. If path "
- "is invalid, clangd will look in the current directory and "
- "parent paths of each source file."));
+ llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
+ "is invalid, clangd will look in the current directory and "
+ "parent paths of each source file."));
-static cl::opt<unsigned>
- WorkerThreadsCount("j", cl::desc("Number of async workers used by clangd"),
- cl::init(getDefaultAsyncThreadsCount()));
+static llvm::cl::opt<unsigned>
+ WorkerThreadsCount("j",
+ llvm::cl::desc("Number of async workers used by clangd"),
+ llvm::cl::init(getDefaultAsyncThreadsCount()));
// FIXME: also support "plain" style where signatures are always omitted.
enum CompletionStyleFlag { Detailed, Bundled };
-static cl::opt<CompletionStyleFlag> CompletionStyle(
- "completion-style", cl::desc("Granularity of code completion suggestions"),
- cl::values(
+static llvm::cl::opt<CompletionStyleFlag> CompletionStyle(
+ "completion-style",
+ llvm::cl::desc("Granularity of code completion suggestions"),
+ llvm::cl::values(
clEnumValN(Detailed, "detailed",
"One completion item for each semantically distinct "
"completion, with full type information."),
clEnumValN(Bundled, "bundled",
"Similar completion items (e.g. function overloads) are "
"combined. Type information shown where possible.")),
- cl::init(Detailed));
+ llvm::cl::init(Detailed));
// FIXME: Flags are the wrong mechanism for user preferences.
// We should probably read a dotfile or similar.
-static cl::opt<bool> IncludeIneligibleResults(
+static llvm::cl::opt<bool> IncludeIneligibleResults(
"include-ineligible-results",
- cl::desc("Include ineligible completion results (e.g. private members)"),
- cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
- cl::Hidden);
-
-static cl::opt<JSONStreamStyle> InputStyle(
- "input-style", cl::desc("Input JSON stream encoding"),
- cl::values(
+ llvm::cl::desc(
+ "Include ineligible completion results (e.g. private members)"),
+ llvm::cl::init(CodeCompleteOptions().IncludeIneligibleResults),
+ llvm::cl::Hidden);
+
+static llvm::cl::opt<JSONStreamStyle> InputStyle(
+ "input-style", llvm::cl::desc("Input JSON stream encoding"),
+ llvm::cl::values(
clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
clEnumValN(JSONStreamStyle::Delimited, "delimited",
"messages delimited by --- lines, with # comment support")),
- cl::init(JSONStreamStyle::Standard));
+ llvm::cl::init(JSONStreamStyle::Standard));
-static cl::opt<bool> PrettyPrint("pretty", cl::desc("Pretty-print JSON output"),
- cl::init(false));
+static llvm::cl::opt<bool>
+ PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
+ llvm::cl::init(false));
-static cl::opt<Logger::Level> LogLevel(
- "log", cl::desc("Verbosity of log messages written to stderr"),
- cl::values(clEnumValN(Logger::Error, "error", "Error messages only"),
- clEnumValN(Logger::Info, "info", "High level execution tracing"),
- clEnumValN(Logger::Debug, "verbose", "Low level details")),
- cl::init(Logger::Info));
+static llvm::cl::opt<Logger::Level> LogLevel(
+ "log", llvm::cl::desc("Verbosity of log messages written to stderr"),
+ llvm::cl::values(clEnumValN(Logger::Error, "error", "Error messages only"),
+ clEnumValN(Logger::Info, "info",
+ "High level execution tracing"),
+ clEnumValN(Logger::Debug, "verbose", "Low level details")),
+ llvm::cl::init(Logger::Info));
-static cl::opt<bool>
+static llvm::cl::opt<bool>
Test("lit-test",
- cl::desc("Abbreviation for -input-style=delimited -pretty "
- "-run-synchronously -enable-test-scheme. "
- "Intended to simplify lit tests."),
- cl::init(false), cl::Hidden);
+ llvm::cl::desc("Abbreviation for -input-style=delimited -pretty "
+ "-run-synchronously -enable-test-scheme. "
+ "Intended to simplify lit tests."),
+ llvm::cl::init(false), llvm::cl::Hidden);
-static cl::opt<bool> EnableTestScheme(
+static llvm::cl::opt<bool> EnableTestScheme(
"enable-test-uri-scheme",
- cl::desc("Enable 'test:' URI scheme. Only use in lit tests."),
- cl::init(false), cl::Hidden);
+ llvm::cl::desc("Enable 'test:' URI scheme. Only use in lit tests."),
+ llvm::cl::init(false), llvm::cl::Hidden);
enum PCHStorageFlag { Disk, Memory };
-static cl::opt<PCHStorageFlag> PCHStorage(
+static llvm::cl::opt<PCHStorageFlag> PCHStorage(
"pch-storage",
- cl::desc("Storing PCHs in memory increases memory usages, but may "
- "improve performance"),
- cl::values(clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
- clEnumValN(PCHStorageFlag::Memory, "memory",
- "store PCHs in memory")),
- cl::init(PCHStorageFlag::Disk));
-
-static cl::opt<int>
- LimitResults("limit-results",
- cl::desc("Limit the number of results returned by clangd. "
- "0 means no limit."),
- cl::init(100));
-
-static cl::opt<bool>
- RunSynchronously("run-synchronously",
- cl::desc("Parse on main thread. If set, -j is ignored"),
- cl::init(false), cl::Hidden);
-
-static cl::opt<Path> ResourceDir("resource-dir",
- cl::desc("Directory for system clang headers"),
- cl::init(""), cl::Hidden);
-
-static cl::opt<Path> InputMirrorFile(
+ llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
+ "improve performance"),
+ llvm::cl::values(
+ clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
+ clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
+ llvm::cl::init(PCHStorageFlag::Disk));
+
+static llvm::cl::opt<int> LimitResults(
+ "limit-results",
+ llvm::cl::desc("Limit the number of results returned by clangd. "
+ "0 means no limit."),
+ llvm::cl::init(100));
+
+static llvm::cl::opt<bool> RunSynchronously(
+ "run-synchronously",
+ llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
+ llvm::cl::init(false), llvm::cl::Hidden);
+
+static llvm::cl::opt<Path>
+ ResourceDir("resource-dir",
+ llvm::cl::desc("Directory for system clang headers"),
+ llvm::cl::init(""), llvm::cl::Hidden);
+
+static llvm::cl::opt<Path> InputMirrorFile(
"input-mirror-file",
- cl::desc(
+ llvm::cl::desc(
"Mirror all LSP input to the specified file. Useful for debugging."),
- cl::init(""), cl::Hidden);
+ llvm::cl::init(""), llvm::cl::Hidden);
-static cl::opt<bool> EnableIndex(
+static llvm::cl::opt<bool> EnableIndex(
"index",
- cl::desc(
+ llvm::cl::desc(
"Enable index-based features. By default, clangd maintains an index "
"built from symbols in opened files. Global index support needs to "
"enabled separatedly."),
- cl::init(true), cl::Hidden);
+ llvm::cl::init(true), llvm::cl::Hidden);
-static cl::opt<bool> AllScopesCompletion(
+static llvm::cl::opt<bool> AllScopesCompletion(
"all-scopes-completion",
- cl::desc(
+ llvm::cl::desc(
"If set to true, code completion will include index symbols that are "
"not defined in the scopes (e.g. "
"namespaces) visible from the code completion point. Such completions "
"can insert scope qualifiers."),
- cl::init(true));
+ llvm::cl::init(true));
-static cl::opt<bool>
- ShowOrigins("debug-origin", cl::desc("Show origins of completion items"),
- cl::init(clangd::CodeCompleteOptions().ShowOrigins),
- cl::Hidden);
+static llvm::cl::opt<bool> ShowOrigins(
+ "debug-origin", llvm::cl::desc("Show origins of completion items"),
+ llvm::cl::init(CodeCompleteOptions().ShowOrigins), llvm::cl::Hidden);
-static cl::opt<bool> HeaderInsertionDecorators(
+static llvm::cl::opt<bool> HeaderInsertionDecorators(
"header-insertion-decorators",
- cl::desc("Prepend a circular dot or space before the completion "
- "label, depending on whether "
- "an include line will be inserted or not."),
- cl::init(true));
+ llvm::cl::desc("Prepend a circular dot or space before the completion "
+ "label, depending on whether "
+ "an include line will be inserted or not."),
+ llvm::cl::init(true));
-static cl::opt<Path> IndexFile(
+static llvm::cl::opt<Path> IndexFile(
"index-file",
- cl::desc(
+ llvm::cl::desc(
"Index file to build the static index. The file must have been created "
"by a compatible clangd-index.\n"
"WARNING: This option is experimental only, and will be removed "
"eventually. Don't rely on it."),
- cl::init(""), cl::Hidden);
+ llvm::cl::init(""), llvm::cl::Hidden);
-static cl::opt<bool> EnableBackgroundIndex(
+static llvm::cl::opt<bool> EnableBackgroundIndex(
"background-index",
- cl::desc("Index project code in the background and persist index on disk. "
- "Experimental"),
- cl::init(false), cl::Hidden);
+ llvm::cl::desc(
+ "Index project code in the background and persist index on disk. "
+ "Experimental"),
+ llvm::cl::init(false), llvm::cl::Hidden);
-static cl::opt<int> BackgroundIndexRebuildPeriod(
+static llvm::cl::opt<int> BackgroundIndexRebuildPeriod(
"background-index-rebuild-period",
- cl::desc(
+ llvm::cl::desc(
"If set to non-zero, the background index rebuilds the symbol index "
"periodically every X milliseconds; otherwise, the "
"symbol index will be updated for each indexed file."),
- cl::init(5000), cl::Hidden);
+ llvm::cl::init(5000), llvm::cl::Hidden);
enum CompileArgsFrom { LSPCompileArgs, FilesystemCompileArgs };
-static cl::opt<CompileArgsFrom> CompileArgsFrom(
- "compile_args_from", cl::desc("The source of compile commands"),
- cl::values(clEnumValN(LSPCompileArgs, "lsp",
- "All compile commands come from LSP and "
- "'compile_commands.json' files are ignored"),
- clEnumValN(FilesystemCompileArgs, "filesystem",
- "All compile commands come from the "
- "'compile_commands.json' files")),
- cl::init(FilesystemCompileArgs), cl::Hidden);
-
-static cl::opt<bool> EnableFunctionArgSnippets(
+static llvm::cl::opt<CompileArgsFrom> CompileArgsFrom(
+ "compile_args_from", llvm::cl::desc("The source of compile commands"),
+ llvm::cl::values(clEnumValN(LSPCompileArgs, "lsp",
+ "All compile commands come from LSP and "
+ "'compile_commands.json' files are ignored"),
+ clEnumValN(FilesystemCompileArgs, "filesystem",
+ "All compile commands come from the "
+ "'compile_commands.json' files")),
+ llvm::cl::init(FilesystemCompileArgs), llvm::cl::Hidden);
+
+static llvm::cl::opt<bool> EnableFunctionArgSnippets(
"function-arg-placeholders",
- cl::desc("When disabled, completions contain only parentheses for "
- "function calls. When enabled, completions also contain "
- "placeholders for method parameters."),
- cl::init(clangd::CodeCompleteOptions().EnableFunctionArgSnippets));
+ llvm::cl::desc("When disabled, completions contain only parentheses for "
+ "function calls. When enabled, completions also contain "
+ "placeholders for method parameters."),
+ llvm::cl::init(CodeCompleteOptions().EnableFunctionArgSnippets));
namespace {
@@ -204,17 +209,18 @@ namespace {
/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
class TestScheme : public URIScheme {
public:
- Expected<std::string> getAbsolutePath(StringRef /*Authority*/, StringRef Body,
- StringRef /*HintPath*/) const override {
+ llvm::Expected<std::string>
+ getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
+ llvm::StringRef /*HintPath*/) const override {
using namespace llvm::sys;
// 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 make_error<StringError>(
+ return llvm::make_error<llvm::StringError>(
"Expect URI body to be an absolute path starting with '/': " + Body,
- inconvertibleErrorCode());
+ llvm::inconvertibleErrorCode());
Body = Body.ltrim('/');
- SmallVector<char, 16> Path(Body.begin(), Body.end());
+ llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
path::native(Path);
auto Err = fs::make_absolute(TestScheme::TestDir, Path);
if (Err)
@@ -222,15 +228,17 @@ public:
return std::string(Path.begin(), Path.end());
}
- Expected<URI> uriFromAbsolutePath(StringRef AbsolutePath) const override {
- StringRef Body = AbsolutePath;
+ llvm::Expected<URI>
+ uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
+ llvm::StringRef Body = AbsolutePath;
if (!Body.consume_front(TestScheme::TestDir)) {
- return make_error<StringError>("Path " + AbsolutePath +
- " doesn't start with root " + TestDir,
- inconvertibleErrorCode());
+ return llvm::make_error<llvm::StringError>(
+ "Path " + AbsolutePath + " doesn't start with root " + TestDir,
+ llvm::inconvertibleErrorCode());
}
- return URI("test", /*Authority=*/"", sys::path::convert_to_slash(Body));
+ return URI("test", /*Authority=*/"",
+ llvm::sys::path::convert_to_slash(Body));
}
private:
@@ -243,14 +251,19 @@ const char TestScheme::TestDir[] = "C:\\clangd-test";
const char TestScheme::TestDir[] = "/clangd-test";
#endif
-}
+} // namespace
+} // namespace clangd
+} // namespace clang
int main(int argc, char *argv[]) {
- sys::PrintStackTraceOnErrorSignal(argv[0]);
- cl::SetVersionPrinter([](raw_ostream &OS) {
+ using namespace clang;
+ using namespace clang::clangd;
+
+ llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
+ llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
OS << clang::getClangToolFullVersion("clangd") << "\n";
});
- cl::ParseCommandLineOptions(
+ llvm::cl::ParseCommandLineOptions(
argc, argv,
"clangd is a language server that provides IDE-like features to editors. "
"\n\nIt should be used via an editor plugin rather than invoked "
@@ -270,26 +283,27 @@ int main(int argc, char *argv[]) {
}
if (!RunSynchronously && WorkerThreadsCount == 0) {
- errs() << "A number of worker threads cannot be 0. Did you mean to "
- "specify -run-synchronously?";
+ llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
+ "specify -run-synchronously?";
return 1;
}
if (RunSynchronously) {
if (WorkerThreadsCount.getNumOccurrences())
- errs() << "Ignoring -j because -run-synchronously is set.\n";
+ llvm::errs() << "Ignoring -j because -run-synchronously is set.\n";
WorkerThreadsCount = 0;
}
// Validate command line arguments.
- Optional<raw_fd_ostream> InputMirrorStream;
+ llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
if (!InputMirrorFile.empty()) {
std::error_code EC;
InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
- sys::fs::FA_Read | sys::fs::FA_Write);
+ llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
if (EC) {
InputMirrorStream.reset();
- errs() << "Error while opening an input mirror file: " << EC.message();
+ llvm::errs() << "Error while opening an input mirror file: "
+ << EC.message();
} else {
InputMirrorStream->SetUnbuffered();
}
@@ -298,51 +312,52 @@ int main(int argc, char *argv[]) {
// Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
// trace flag in your editor's config is annoying, launching with
// `CLANGD_TRACE=trace.json vim` is easier.
- Optional<raw_fd_ostream> TraceStream;
+ llvm::Optional<llvm::raw_fd_ostream> TraceStream;
std::unique_ptr<trace::EventTracer> Tracer;
if (auto *TraceFile = getenv("CLANGD_TRACE")) {
std::error_code EC;
TraceStream.emplace(TraceFile, /*ref*/ EC,
- sys::fs::FA_Read | sys::fs::FA_Write);
+ llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
if (EC) {
TraceStream.reset();
- errs() << "Error while opening trace file " << TraceFile << ": "
- << EC.message();
+ llvm::errs() << "Error while opening trace file " << TraceFile << ": "
+ << EC.message();
} else {
Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
}
}
- Optional<trace::Session> TracingSession;
+ llvm::Optional<trace::Session> TracingSession;
if (Tracer)
TracingSession.emplace(*Tracer);
// Use buffered stream to stderr (we still flush each log message). Unbuffered
// stream can cause significant (non-deterministic) latency for the logger.
- errs().SetBuffered();
- StreamLogger Logger(errs(), LogLevel);
- clangd::LoggingSession LoggingSession(Logger);
+ llvm::errs().SetBuffered();
+ StreamLogger Logger(llvm::errs(), LogLevel);
+ LoggingSession LoggingSession(Logger);
// If --compile-commands-dir arg was invoked, check value and override default
// path.
- Optional<Path> CompileCommandsDirPath;
+ llvm::Optional<Path> CompileCommandsDirPath;
if (!CompileCommandsDir.empty()) {
- if (sys::fs::exists(CompileCommandsDir)) {
+ if (llvm::sys::fs::exists(CompileCommandsDir)) {
// We support passing both relative and absolute paths to the
// --compile-commands-dir argument, but we assume the path is absolute in
// the rest of clangd so we make sure the path is absolute before
// continuing.
- SmallString<128> Path(CompileCommandsDir);
- if (std::error_code EC = sys::fs::make_absolute(Path)) {
- errs() << "Error while converting the relative path specified by "
- "--compile-commands-dir to an absolute path: "
- << EC.message() << ". The argument will be ignored.\n";
+ llvm::SmallString<128> Path(CompileCommandsDir);
+ if (std::error_code EC = llvm::sys::fs::make_absolute(Path)) {
+ llvm::errs() << "Error while converting the relative path specified by "
+ "--compile-commands-dir to an absolute path: "
+ << EC.message() << ". The argument will be ignored.\n";
} else {
CompileCommandsDirPath = Path.str();
}
} else {
- errs() << "Path specified by --compile-commands-dir does not exist. The "
- "argument will be ignored.\n";
+ llvm::errs()
+ << "Path specified by --compile-commands-dir does not exist. The "
+ "argument will be ignored.\n";
}
}
@@ -392,15 +407,15 @@ int main(int argc, char *argv[]) {
// Initialize and run ClangdLSPServer.
// Change stdin to binary to not lose \r\n on windows.
- sys::ChangeStdinToBinary();
+ llvm::sys::ChangeStdinToBinary();
auto Transport = newJSONTransport(
- stdin, outs(),
+ stdin, llvm::outs(),
InputMirrorStream ? InputMirrorStream.getPointer() : nullptr, PrettyPrint,
InputStyle);
ClangdLSPServer LSPServer(
*Transport, CCOpts, CompileCommandsDirPath,
/*UseDirBasedCDB=*/CompileArgsFrom == FilesystemCompileArgs, Opts);
constexpr int NoShutdownRequestErrorCode = 1;
- set_thread_name("clangd.main");
+ llvm::set_thread_name("clangd.main");
return LSPServer.run() ? 0 : NoShutdownRequestErrorCode;
}