[clang-tools-extra] r344850 - [clangd] Namespace style cleanup in cpp files. NFC.
Sam McCall via cfe-commits
cfe-commits at lists.llvm.org
Sat Oct 20 08:30:38 PDT 2018
Author: sammccall
Date: Sat Oct 20 08:30:37 2018
New Revision: 344850
URL: http://llvm.org/viewvc/llvm-project?rev=344850&view=rev
Log:
[clangd] Namespace style cleanup in cpp files. NFC.
Standardize on the most common namespace setup in our *.cpp files:
using namespace llvm;
namespace clang {
namespace clangd {
void foo(StringRef) { ... }
And remove redundant llvm:: qualifiers. (Except for cases like
make_unique where this causes problems with std:: and ADL).
This choice is pretty arbitrary, but some broad consistency is nice.
This is going to conflict with everything. Sorry :-/
Squash the other configurations:
A)
using namespace llvm;
using namespace clang;
using namespace clangd;
void clangd::foo(StringRef);
This is in some of the older files. (It prevents accidentally defining a
new function instead of one in the header file, for what that's worth).
B)
namespace clang {
namespace clangd {
void foo(llvm::StringRef) { ... }
This is fine, but in practice the using directive often gets added over time.
C)
namespace clang {
namespace clangd {
using namespace llvm; // inside the namespace
This was pretty common, but is a bit misleading: name lookup preferrs
clang::clangd::foo > clang::foo > llvm:: foo (no matter where the using
directive is).
Modified:
clang-tools-extra/trunk/clangd/AST.cpp
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdUnit.cpp
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp
clang-tools-extra/trunk/clangd/Compiler.cpp
clang-tools-extra/trunk/clangd/Diagnostics.cpp
clang-tools-extra/trunk/clangd/DraftStore.cpp
clang-tools-extra/trunk/clangd/FS.cpp
clang-tools-extra/trunk/clangd/FileDistance.cpp
clang-tools-extra/trunk/clangd/FindSymbols.cpp
clang-tools-extra/trunk/clangd/FuzzyMatch.cpp
clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp
clang-tools-extra/trunk/clangd/Headers.cpp
clang-tools-extra/trunk/clangd/JSONTransport.cpp
clang-tools-extra/trunk/clangd/Logger.cpp
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/clangd/Quality.cpp
clang-tools-extra/trunk/clangd/RIFF.cpp
clang-tools-extra/trunk/clangd/SourceCode.cpp
clang-tools-extra/trunk/clangd/TUScheduler.cpp
clang-tools-extra/trunk/clangd/Threading.cpp
clang-tools-extra/trunk/clangd/Trace.cpp
clang-tools-extra/trunk/clangd/URI.cpp
clang-tools-extra/trunk/clangd/XRefs.cpp
clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp
clang-tools-extra/trunk/clangd/index/Background.cpp
clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp
clang-tools-extra/trunk/clangd/index/FileIndex.cpp
clang-tools-extra/trunk/clangd/index/Index.cpp
clang-tools-extra/trunk/clangd/index/IndexAction.cpp
clang-tools-extra/trunk/clangd/index/MemIndex.cpp
clang-tools-extra/trunk/clangd/index/Merge.cpp
clang-tools-extra/trunk/clangd/index/Serialization.cpp
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
clang-tools-extra/trunk/clangd/index/dex/Dex.cpp
clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp
clang-tools-extra/trunk/clangd/index/dex/Trigram.cpp
clang-tools-extra/trunk/clangd/index/dex/dexp/Dexp.cpp
clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp
clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
clang-tools-extra/trunk/unittests/clangd/Annotations.cpp
clang-tools-extra/trunk/unittests/clangd/CancellationTests.cpp
clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
clang-tools-extra/trunk/unittests/clangd/DexTests.cpp
clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp
clang-tools-extra/trunk/unittests/clangd/FSTests.cpp
clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp
clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp
clang-tools-extra/trunk/unittests/clangd/GlobalCompilationDatabaseTests.cpp
clang-tools-extra/trunk/unittests/clangd/HeadersTests.cpp
clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp
clang-tools-extra/trunk/unittests/clangd/JSONTransportTests.cpp
clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp
clang-tools-extra/trunk/unittests/clangd/RIFFTests.cpp
clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp
clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp
clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
clang-tools-extra/trunk/unittests/clangd/SyncAPI.cpp
clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
clang-tools-extra/trunk/unittests/clangd/TestFS.cpp
clang-tools-extra/trunk/unittests/clangd/TestIndex.cpp
clang-tools-extra/trunk/unittests/clangd/TestTU.cpp
clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp
clang-tools-extra/trunk/unittests/clangd/URITests.cpp
clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp
Modified: clang-tools-extra/trunk/clangd/AST.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/AST.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/AST.cpp (original)
+++ clang-tools-extra/trunk/clangd/AST.cpp Sat Oct 20 08:30:37 2018
@@ -15,9 +15,9 @@
#include "clang/Basic/SourceManager.h"
#include "clang/Index/USRGeneration.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
// Returns true if the complete name of decl \p D is spelled in the source code.
// This is not the case for
@@ -32,8 +32,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 (llvm::StringRef(PrintLoc).startswith("<scratch") ||
- llvm::StringRef(PrintLoc).startswith("<command line>"))
+ if (StringRef(PrintLoc).startswith("<scratch") ||
+ StringRef(PrintLoc).startswith("<command line>"))
return false;
}
return true;
@@ -51,7 +51,7 @@ SourceLocation findNameLoc(const clang::
std::string printQualifiedName(const NamedDecl &ND) {
std::string QName;
- llvm::raw_string_ostream OS(QName);
+ 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
@@ -72,19 +72,18 @@ std::string printNamespaceScope(const De
return "";
}
-llvm::Optional<SymbolID> getSymbolID(const Decl *D) {
- llvm::SmallString<128> USR;
+Optional<SymbolID> getSymbolID(const Decl *D) {
+ SmallString<128> USR;
if (index::generateUSRForDecl(D, USR))
return None;
return SymbolID(USR);
}
-llvm::Optional<SymbolID> getSymbolID(const IdentifierInfo &II,
- const MacroInfo *MI,
- const SourceManager &SM) {
+Optional<SymbolID> getSymbolID(const IdentifierInfo &II, const MacroInfo *MI,
+ const SourceManager &SM) {
if (MI == nullptr)
return None;
- llvm::SmallString<128> USR;
+ SmallString<128> USR;
if (index::generateUSRForMacro(II.getName(), MI->getDefinitionLoc(), SM, USR))
return None;
return SymbolID(USR);
Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Sat Oct 20 08:30:37 2018
@@ -18,10 +18,9 @@
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
-using namespace clang::clangd;
-using namespace clang;
using namespace llvm;
-
+namespace clang {
+namespace clangd {
namespace {
/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
@@ -30,23 +29,22 @@ namespace {
/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
class TestScheme : public URIScheme {
public:
- llvm::Expected<std::string>
- getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
- llvm::StringRef /*HintPath*/) const override {
+ Expected<std::string> getAbsolutePath(StringRef /*Authority*/, StringRef Body,
+ 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 llvm::make_error<llvm::StringError>(
+ return make_error<StringError>(
"Expect URI body to be an absolute path starting with '/': " + Body,
- llvm::inconvertibleErrorCode());
+ inconvertibleErrorCode());
Body = Body.ltrim('/');
#ifdef _WIN32
constexpr char TestDir[] = "C:\\clangd-test";
#else
constexpr char TestDir[] = "/clangd-test";
#endif
- llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
+ SmallVector<char, 16> Path(Body.begin(), Body.end());
path::native(Path);
auto Err = fs::make_absolute(TestDir, Path);
if (Err)
@@ -54,8 +52,7 @@ public:
return std::string(Path.begin(), Path.end());
}
- llvm::Expected<URI>
- uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
+ Expected<URI> uriFromAbsolutePath(StringRef AbsolutePath) const override {
llvm_unreachable("Clangd must never create a test URI.");
}
};
@@ -116,8 +113,8 @@ public:
} else if (auto Handler = Calls.lookup(Method))
Handler(std::move(Params), std::move(ID));
else
- Server.reply(ID, llvm::make_error<LSPError>("method not found",
- ErrorCode::MethodNotFound));
+ Server.reply(ID, make_error<LSPError>("method not found",
+ ErrorCode::MethodNotFound));
return true;
}
@@ -126,7 +123,7 @@ public:
if (Result)
log("<-- reply({0})", ID);
else
- log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
+ log("<-- reply({0}) error: {1}", ID, toString(Result.takeError()));
return true;
}
@@ -149,7 +146,7 @@ public:
// Calls can be canceled by the client. Add cancellation context.
WithContext WithCancel(cancelableRequestContext(ID));
// FIXME: this function should assert it's called exactly once.
- (Server.*Handler)(P, [this, ID, Trace](llvm::Expected<Reply> Result) {
+ (Server.*Handler)(P, [this, ID, Trace](Expected<Reply> Result) {
if (Result) {
if (Trace)
(*Trace)["Reply"] = *Result;
@@ -157,7 +154,7 @@ public:
} else {
auto Err = Result.takeError();
if (Trace)
- (*Trace)["Error"] = llvm::to_string(Err);
+ (*Trace)["Error"] = to_string(Err);
Server.reply(ID, std::move(Err));
}
});
@@ -181,16 +178,16 @@ public:
}
private:
- llvm::StringMap<std::function<void(json::Value)>> Notifications;
- llvm::StringMap<std::function<void(json::Value, json::Value)>> Calls;
+ StringMap<std::function<void(json::Value)>> Notifications;
+ StringMap<std::function<void(json::Value, json::Value)>> 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;
- llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
+ StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
- void onCancel(const llvm::json::Value &Params) {
+ void onCancel(const json::Value &Params) {
const json::Value *ID = nullptr;
if (auto *O = Params.getAsObject())
ID = O->get("id");
@@ -198,7 +195,7 @@ private:
elog("Bad cancellation request: {0}", Params);
return;
}
- auto StrID = llvm::to_string(*ID);
+ auto StrID = to_string(*ID);
std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
auto It = RequestCancelers.find(StrID);
if (It != RequestCancelers.end())
@@ -210,7 +207,7 @@ private:
// If a client reuses an ID, the last wins and the first cannot be canceled.
Context cancelableRequestContext(const json::Value &ID) {
auto Task = cancelableTask();
- auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
+ auto StrID = 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);
@@ -245,8 +242,7 @@ void ClangdLSPServer::notify(StringRef M
Transp.notify(Method, std::move(Params));
}
-void ClangdLSPServer::reply(llvm::json::Value ID,
- llvm::Expected<llvm::json::Value> Result) {
+void ClangdLSPServer::reply(json::Value ID, Expected<json::Value> Result) {
if (Result) {
log("--> reply({0})", ID);
std::lock_guard<std::mutex> Lock(TranspWriter);
@@ -352,7 +348,7 @@ void ClangdLSPServer::onDocumentDidChang
: WantDiagnostics::No;
PathRef File = Params.textDocument.uri.file();
- llvm::Expected<std::string> Contents =
+ 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
@@ -399,7 +395,7 @@ void ClangdLSPServer::onCommand(const Ex
// 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>(
- llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
+ formatv("Unsupported command \"{0}\".", Params.command).str(),
ErrorCode::InvalidParams));
}
}
@@ -411,7 +407,7 @@ void ClangdLSPServer::onWorkspaceSymbol(
Params.query, CCOpts.Limit,
Bind(
[this](decltype(Reply) Reply,
- llvm::Expected<std::vector<SymbolInformation>> Items) {
+ Expected<std::vector<SymbolInformation>> Items) {
if (!Items)
return Reply(Items.takeError());
for (auto &Sym : *Items)
@@ -425,7 +421,7 @@ void ClangdLSPServer::onWorkspaceSymbol(
void ClangdLSPServer::onRename(const RenameParams &Params,
Callback<WorkspaceEdit> Reply) {
Path File = Params.textDocument.uri.file();
- llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
+ Optional<std::string> Code = DraftMgr.getDraft(File);
if (!Code)
return Reply(make_error<LSPError>("onRename called for non-added file",
ErrorCode::InvalidParams));
@@ -433,9 +429,9 @@ void ClangdLSPServer::onRename(const Ren
Server->rename(
File, Params.position, Params.newName,
Bind(
- [File, Code, Params](
- decltype(Reply) Reply,
- llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
+ [File, Code,
+ Params](decltype(Reply) Reply,
+ Expected<std::vector<tooling::Replacement>> Replacements) {
if (!Replacements)
return Reply(Replacements.takeError());
@@ -517,7 +513,7 @@ void ClangdLSPServer::onDocumentSymbol(
Params.textDocument.uri.file(),
Bind(
[this](decltype(Reply) Reply,
- llvm::Expected<std::vector<SymbolInformation>> Items) {
+ Expected<std::vector<SymbolInformation>> Items) {
if (!Items)
return Reply(Items.takeError());
for (auto &Sym : *Items)
@@ -530,14 +526,14 @@ void ClangdLSPServer::onDocumentSymbol(
static Optional<Command> asCommand(const CodeAction &Action) {
Command Cmd;
if (Action.command && Action.edit)
- return llvm::None; // Not representable. (We never emit these anyway).
+ return None; // Not representable. (We never emit these anyway).
if (Action.command) {
Cmd = *Action.command;
} else if (Action.edit) {
Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
Cmd.workspaceEdit = *Action.edit;
} else {
- return llvm::None;
+ return None;
}
Cmd.title = Action.title;
if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
@@ -582,7 +578,7 @@ void ClangdLSPServer::onCompletion(const
Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Bind(
[this](decltype(Reply) Reply,
- llvm::Expected<CodeCompleteResult> List) {
+ Expected<CodeCompleteResult> List) {
if (!List)
return Reply(List.takeError());
CompletionList LSPList;
@@ -612,7 +608,7 @@ void ClangdLSPServer::onGoToDefinition(c
void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
Callback<std::string> Reply) {
- llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
+ Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Reply(Result ? URI::createFile(*Result).toString() : "");
}
@@ -624,7 +620,7 @@ void ClangdLSPServer::onDocumentHighligh
}
void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
- Callback<llvm::Optional<Hover>> Reply) {
+ Callback<Optional<Hover>> Reply) {
Server->findHover(Params.textDocument.uri.file(), Params.position,
std::move(Reply));
}
@@ -665,7 +661,7 @@ void ClangdLSPServer::onReference(const
ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
const clangd::CodeCompleteOptions &CCOpts,
- llvm::Optional<Path> CompileCommandsDir,
+ Optional<Path> CompileCommandsDir,
bool ShouldUseInMemoryCDB,
const ClangdServer::Options &Opts)
: Transp(Transp), MsgHandler(new MessageHandler(*this)),
@@ -737,7 +733,7 @@ void ClangdLSPServer::onDiagnosticsReady
DiagnosticToReplacementMap LocalFixIts; // Temporary storage
for (auto &Diag : Diagnostics) {
- toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
+ toLSPDiags(Diag, [&](clangd::Diagnostic Diag, ArrayRef<Fix> Fixes) {
json::Object LSPDiag({
{"range", Diag.range},
{"severity", Diag.severity},
@@ -793,7 +789,7 @@ ClangdLSPServer::CompilationDB ClangdLSP
ClangdLSPServer::CompilationDB
ClangdLSPServer::CompilationDB::makeDirectoryBased(
- llvm::Optional<Path> CompileCommandsDir) {
+ Optional<Path> CompileCommandsDir) {
auto CDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
std::move(CompileCommandsDir));
auto CachingCDB = llvm::make_unique<CachingCompilationDb>(*CDB);
@@ -849,3 +845,6 @@ GlobalCompilationDatabase &ClangdLSPServ
return *CachingCDB;
return *CDB;
}
+
+} // namespace clangd
+} // namespace clang
Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Sat Oct 20 08:30:37 2018
@@ -34,13 +34,13 @@
#include <future>
#include <mutex>
-using namespace clang;
-using namespace clang::clangd;
-
+using namespace llvm;
+namespace clang {
+namespace clangd {
namespace {
-void ignoreError(llvm::Error Err) {
- handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
+void ignoreError(Error Err) {
+ handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
}
std::string getStandardResourceDir() {
@@ -51,7 +51,7 @@ std::string getStandardResourceDir() {
class RefactoringResultCollector final
: public tooling::RefactoringResultConsumer {
public:
- void handleError(llvm::Error Err) override {
+ void handleError(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
@@ -164,13 +164,13 @@ void ClangdServer::codeComplete(PathRef
auto Task = [PCHs, Pos, FS, CodeCompleteOpts,
this](Path File, Callback<CodeCompleteResult> CB,
- llvm::Expected<InputsAndPreamble> IP) {
+ Expected<InputsAndPreamble> IP) {
if (!IP)
return CB(IP.takeError());
if (isCancelled())
- return CB(llvm::make_error<CancelledError>());
+ return CB(make_error<CancelledError>());
- llvm::Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
+ Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
if (CodeCompleteOpts.Index && CodeCompleteOpts.SpeculativeIndexRequest) {
SpecFuzzyFind.emplace();
{
@@ -211,7 +211,7 @@ void ClangdServer::signatureHelp(PathRef
auto FS = FSProvider.getFileSystem();
auto *Index = this->Index;
auto Action = [Pos, FS, PCHs, Index](Path File, Callback<SignatureHelp> CB,
- llvm::Expected<InputsAndPreamble> IP) {
+ Expected<InputsAndPreamble> IP) {
if (!IP)
return CB(IP.takeError());
@@ -228,28 +228,28 @@ void ClangdServer::signatureHelp(PathRef
Bind(Action, File.str(), std::move(CB)));
}
-llvm::Expected<tooling::Replacements>
+Expected<tooling::Replacements>
ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
- llvm::Expected<size_t> Begin = positionToOffset(Code, Rng.start);
+ Expected<size_t> Begin = positionToOffset(Code, Rng.start);
if (!Begin)
return Begin.takeError();
- llvm::Expected<size_t> End = positionToOffset(Code, Rng.end);
+ Expected<size_t> End = positionToOffset(Code, Rng.end);
if (!End)
return End.takeError();
return formatCode(Code, File, {tooling::Range(*Begin, *End - *Begin)});
}
-llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
- PathRef File) {
+Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
+ PathRef File) {
// Format everything.
return formatCode(Code, File, {tooling::Range(0, Code.size())});
}
-llvm::Expected<tooling::Replacements>
+Expected<tooling::Replacements>
ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
// Look for the previous opening brace from the character position and
// format starting from there.
- llvm::Expected<size_t> CursorPos = positionToOffset(Code, Pos);
+ Expected<size_t> CursorPos = positionToOffset(Code, Pos);
if (!CursorPos)
return CursorPos.takeError();
size_t PreviousLBracePos = StringRef(Code).find_last_of('{', *CursorPos);
@@ -260,7 +260,7 @@ ClangdServer::formatOnType(StringRef Cod
return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
}
-void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
+void ClangdServer::rename(PathRef File, Position Pos, StringRef NewName,
Callback<std::vector<tooling::Replacement>> CB) {
auto Action = [Pos](Path File, std::string NewName,
Callback<std::vector<tooling::Replacement>> CB,
@@ -312,16 +312,15 @@ void ClangdServer::rename(PathRef File,
}
void ClangdServer::dumpAST(PathRef File,
- llvm::unique_function<void(std::string)> Callback) {
- auto Action = [](decltype(Callback) Callback,
- llvm::Expected<InputsAndAST> InpAST) {
+ unique_function<void(std::string)> Callback) {
+ auto Action = [](decltype(Callback) Callback, Expected<InputsAndAST> InpAST) {
if (!InpAST) {
ignoreError(InpAST.takeError());
return Callback("<no-ast>");
}
std::string Result;
- llvm::raw_string_ostream ResultOS(Result);
+ raw_string_ostream ResultOS(Result);
clangd::dumpAST(InpAST->AST, ResultOS);
ResultOS.flush();
@@ -334,7 +333,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,
- llvm::Expected<InputsAndAST> InpAST) {
+ Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
CB(clangd::findDefinitions(InpAST->AST, Pos, Index));
@@ -343,13 +342,13 @@ void ClangdServer::findDefinitions(PathR
WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
}
-llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
+Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
".c++", ".m", ".mm"};
StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
- StringRef PathExt = llvm::sys::path::extension(Path);
+ StringRef PathExt = sys::path::extension(Path);
// Lookup in a list of known extensions.
auto SourceIter =
@@ -367,7 +366,7 @@ llvm::Optional<Path> ClangdServer::switc
// We can only switch between the known extensions.
if (!IsSource && !IsHeader)
- return llvm::None;
+ return None;
// Array to lookup extensions for the switch. An opposite of where original
// extension was found.
@@ -385,23 +384,23 @@ llvm::Optional<Path> ClangdServer::switc
// Loop through switched extension candidates.
for (StringRef NewExt : NewExts) {
- llvm::sys::path::replace_extension(NewPath, NewExt);
+ 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.
- llvm::sys::path::replace_extension(NewPath, NewExt.upper());
+ sys::path::replace_extension(NewPath, NewExt.upper());
if (FS->exists(NewPath))
return NewPath.str().str();
}
- return llvm::None;
+ return None;
}
-llvm::Expected<tooling::Replacements>
-ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
+Expected<tooling::Replacements>
+ClangdServer::formatCode(StringRef Code, PathRef File,
ArrayRef<tooling::Range> Ranges) {
// Call clang-format.
auto FS = FSProvider.getFileSystem();
@@ -425,7 +424,7 @@ ClangdServer::formatCode(llvm::StringRef
void ClangdServer::findDocumentHighlights(
PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
auto Action = [Pos](Callback<std::vector<DocumentHighlight>> CB,
- llvm::Expected<InputsAndAST> InpAST) {
+ Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
@@ -435,9 +434,9 @@ void ClangdServer::findDocumentHighlight
}
void ClangdServer::findHover(PathRef File, Position Pos,
- Callback<llvm::Optional<Hover>> CB) {
- auto Action = [Pos](Callback<llvm::Optional<Hover>> CB,
- llvm::Expected<InputsAndAST> InpAST) {
+ Callback<Optional<Hover>> CB) {
+ auto Action = [Pos](Callback<Optional<Hover>> CB,
+ Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
CB(clangd::getHover(InpAST->AST, Pos));
@@ -466,7 +465,7 @@ void ClangdServer::consumeDiagnostics(Pa
tooling::CompileCommand ClangdServer::getCompileCommand(PathRef File) {
trace::Span Span("GetCompileCommand");
- llvm::Optional<tooling::CompileCommand> C = CDB.getCompileCommand(File);
+ Optional<tooling::CompileCommand> C = CDB.getCompileCommand(File);
if (!C) // FIXME: Suppress diagnostics? Let the user know?
C = CDB.getFallbackCommand(File);
@@ -490,7 +489,7 @@ void ClangdServer::workspaceSymbols(
void ClangdServer::documentSymbols(
StringRef File, Callback<std::vector<SymbolInformation>> CB) {
auto Action = [](Callback<std::vector<SymbolInformation>> CB,
- llvm::Expected<InputsAndAST> InpAST) {
+ Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
CB(clangd::getDocumentSymbols(InpAST->AST));
@@ -502,7 +501,7 @@ void ClangdServer::documentSymbols(
void ClangdServer::findReferences(PathRef File, Position Pos,
Callback<std::vector<Location>> CB) {
auto Action = [Pos, this](Callback<std::vector<Location>> CB,
- llvm::Expected<InputsAndAST> InpAST) {
+ Expected<InputsAndAST> InpAST) {
if (!InpAST)
return CB(InpAST.takeError());
CB(clangd::findReferences(InpAST->AST, Pos, Index));
@@ -517,6 +516,9 @@ ClangdServer::getUsedBytesPerFile() cons
}
LLVM_NODISCARD bool
-ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
+ClangdServer::blockUntilIdleForTest(Optional<double> TimeoutSeconds) {
return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
}
+
+} // namespace clangd
+} // namespace clang
Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Sat Oct 20 08:30:37 2018
@@ -34,16 +34,16 @@
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
-using namespace clang::clangd;
-using namespace clang;
-
+using namespace llvm;
+namespace clang {
+namespace clangd {
namespace {
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 &&
- llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
+ makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
}
template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
@@ -116,16 +116,16 @@ private:
} // namespace
-void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
+void dumpAST(ParsedAST &AST, raw_ostream &OS) {
AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
}
-llvm::Optional<ParsedAST>
-ParsedAST::build(std::unique_ptr<clang::CompilerInvocation> CI,
+Optional<ParsedAST>
+ParsedAST::build(std::unique_ptr<CompilerInvocation> CI,
std::shared_ptr<const PreambleData> Preamble,
- std::unique_ptr<llvm::MemoryBuffer> Buffer,
+ std::unique_ptr<MemoryBuffer> Buffer,
std::shared_ptr<PCHContainerOperations> PCHs,
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
+ IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
assert(CI);
// Command-line parsing sets DisableFree to true by default, but we don't want
// to leak memory in clangd.
@@ -138,14 +138,14 @@ ParsedAST::build(std::unique_ptr<clang::
prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer),
std::move(PCHs), std::move(VFS), ASTDiags);
if (!Clang)
- return llvm::None;
+ return None;
auto Action = llvm::make_unique<ClangdFrontendAction>();
const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
if (!Action->BeginSourceFile(*Clang, MainInput)) {
log("BeginSourceFile() failed when building AST for {0}",
MainInput.getFile());
- return llvm::None;
+ return None;
}
// Copy over the includes from the preamble, then combine with the
@@ -210,7 +210,7 @@ std::size_t ParsedAST::getUsedBytes() co
// FIXME(ibiryukov): we do not account for the dynamically allocated part of
// Message and Fixes inside each diagnostic.
std::size_t Total =
- ::getUsedBytes(LocalTopLevelDecls) + ::getUsedBytes(Diags);
+ clangd::getUsedBytes(LocalTopLevelDecls) + clangd::getUsedBytes(Diags);
// FIXME: the rest of the function is almost a direct copy-paste from
// libclang's clang_getCXTUResourceUsage. We could share the implementation.
@@ -261,7 +261,7 @@ ParsedAST::ParsedAST(std::shared_ptr<con
}
std::unique_ptr<CompilerInvocation>
-clangd::buildCompilerInvocation(const ParseInputs &Inputs) {
+buildCompilerInvocation(const ParseInputs &Inputs) {
std::vector<const char *> ArgStrs;
for (const auto &S : Inputs.CompileCommand.CommandLine)
ArgStrs.push_back(S.c_str());
@@ -288,15 +288,16 @@ clangd::buildCompilerInvocation(const Pa
return CI;
}
-std::shared_ptr<const PreambleData> clangd::buildPreamble(
- PathRef FileName, CompilerInvocation &CI,
- std::shared_ptr<const PreambleData> OldPreamble,
- const tooling::CompileCommand &OldCompileCommand, const ParseInputs &Inputs,
- std::shared_ptr<PCHContainerOperations> PCHs, bool StoreInMemory,
- PreambleParsedCallback PreambleCallback) {
+std::shared_ptr<const PreambleData>
+buildPreamble(PathRef FileName, CompilerInvocation &CI,
+ std::shared_ptr<const PreambleData> OldPreamble,
+ const tooling::CompileCommand &OldCompileCommand,
+ const ParseInputs &Inputs,
+ std::shared_ptr<PCHContainerOperations> PCHs, bool StoreInMemory,
+ PreambleParsedCallback PreambleCallback) {
// Note that we don't need to copy the input contents, preamble can live
// without those.
- auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Inputs.Contents);
+ auto ContentsBuffer = MemoryBuffer::getMemBuffer(Inputs.Contents);
auto Bounds =
ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
@@ -332,7 +333,7 @@ std::shared_ptr<const PreambleData> clan
// dirs.
}
- llvm::SmallString<32> AbsFileName(FileName);
+ SmallString<32> AbsFileName(FileName);
Inputs.FS->makeAbsolute(AbsFileName);
auto StatCache = llvm::make_unique<PreambleFileStatusCache>(AbsFileName);
auto BuiltPreamble = PrecompiledPreamble::Build(
@@ -356,10 +357,11 @@ std::shared_ptr<const PreambleData> clan
}
}
-llvm::Optional<ParsedAST> clangd::buildAST(
- PathRef FileName, std::unique_ptr<CompilerInvocation> Invocation,
- const ParseInputs &Inputs, std::shared_ptr<const PreambleData> Preamble,
- std::shared_ptr<PCHContainerOperations> PCHs) {
+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);
@@ -372,15 +374,13 @@ llvm::Optional<ParsedAST> clangd::buildA
// dirs.
}
- return ParsedAST::build(llvm::make_unique<CompilerInvocation>(*Invocation),
- Preamble,
- llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents),
- PCHs, std::move(VFS));
+ return ParsedAST::build(
+ llvm::make_unique<CompilerInvocation>(*Invocation), Preamble,
+ MemoryBuffer::getMemBufferCopy(Inputs.Contents), PCHs, std::move(VFS));
}
-SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
- const Position &Pos,
- const FileID FID) {
+SourceLocation getBeginningOfIdentifier(ParsedAST &Unit, const Position &Pos,
+ const FileID FID) {
const ASTContext &AST = Unit.getASTContext();
const SourceManager &SourceMgr = AST.getSourceManager();
auto Offset = positionToOffset(SourceMgr.getBufferData(FID), Pos);
@@ -411,3 +411,6 @@ SourceLocation clangd::getBeginningOfIde
return SourceMgr.getMacroArgExpandedLocation(Before); // Case 2.
return SourceMgr.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
}
+
+} // namespace clangd
+} // namespace clang
Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Sat Oct 20 08:30:37 2018
@@ -59,6 +59,7 @@
// We log detailed candidate here if you run with -debug-only=codecomplete.
#define DEBUG_TYPE "CodeComplete"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -180,8 +181,7 @@ std::string getOptionalParameters(const
/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
/// include.
-static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
- llvm::StringRef HintPath) {
+static Expected<HeaderFile> toHeaderFile(StringRef Header, StringRef HintPath) {
if (isLiteralInclude(Header))
return HeaderFile{Header.str(), /*Verbatim=*/true};
auto U = URI::parse(Header);
@@ -203,11 +203,11 @@ static llvm::Expected<HeaderFile> toHead
/// 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 {
- llvm::StringRef Name; // Used for filtering and sorting.
+ 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;
- llvm::SmallVector<StringRef, 1> RankedIncludeHeaders;
+ SmallVector<StringRef, 1> RankedIncludeHeaders;
// Returns a token identifying the overload set this is part of.
// 0 indicates it's not part of any overload set.
@@ -236,28 +236,28 @@ struct CompletionCandidate {
if (!D || !D->isFunctionOrFunctionTemplate())
return 0;
{
- llvm::raw_svector_ostream OS(Scratch);
+ raw_svector_ostream OS(Scratch);
D->printQualifiedName(OS);
}
return hash_combine(Scratch, headerToInsertIfAllowed().getValueOr(""));
}
// The best header to include if include insertion is allowed.
- llvm::Optional<llvm::StringRef> headerToInsertIfAllowed() const {
+ Optional<StringRef> headerToInsertIfAllowed() const {
if (RankedIncludeHeaders.empty())
- return llvm::None;
+ return None;
if (SemaResult && SemaResult->Declaration) {
// Avoid inserting new #include if the declaration is found in the current
// file e.g. the symbol is forward declared.
auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
for (const Decl *RD : SemaResult->Declaration->redecls())
if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
- return llvm::None;
+ return None;
}
return RankedIncludeHeaders[0];
}
- using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
+ using Bundle = SmallVector<CompletionCandidate, 4>;
};
using ScoredBundle =
std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
@@ -280,7 +280,7 @@ struct ScoredBundleGreater {
struct CodeCompletionBuilder {
CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
CodeCompletionString *SemaCCS,
- llvm::ArrayRef<std::string> QueryScopes,
+ ArrayRef<std::string> QueryScopes,
const IncludeInserter &Includes, StringRef FileName,
CodeCompletionContext::Kind ContextKind,
const CodeCompleteOptions &Opts)
@@ -289,12 +289,12 @@ struct CodeCompletionBuilder {
add(C, SemaCCS);
if (C.SemaResult) {
Completion.Origin |= SymbolOrigin::AST;
- Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
+ Completion.Name = StringRef(SemaCCS->getTypedText());
if (Completion.Scope.empty()) {
if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
(C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
if (const auto *D = C.SemaResult->getDeclaration())
- if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
+ if (const auto *ND = dyn_cast<NamedDecl>(D))
Completion.Scope =
splitQualifiedName(printQualifiedName(*ND)).first;
}
@@ -459,7 +459,7 @@ private:
// foo<${1:class}>(${2:int p1}).
// We transform this pattern to '<$1>()$0' or '<$0>()'.
- bool EmptyArgs = llvm::StringRef(*Snippet).endswith("()");
+ bool EmptyArgs = StringRef(*Snippet).endswith("()");
if (Snippet->front() == '<')
return EmptyArgs ? "<$1>()$0" : "<$1>($0)";
if (Snippet->front() == '(')
@@ -473,7 +473,7 @@ private:
// Classes and template using aliases can only have template arguments,
// e.g. Foo<${1:class}>.
- if (llvm::StringRef(*Snippet).endswith("<>"))
+ if (StringRef(*Snippet).endswith("<>"))
return "<>"; // can happen with defaulted template arguments.
return "<$0>";
}
@@ -495,8 +495,8 @@ private:
};
// Determine the symbol ID for a Sema code completion result, if possible.
-llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R,
- const SourceManager &SM) {
+Optional<SymbolID> getSymbolID(const CodeCompletionResult &R,
+ const SourceManager &SM) {
switch (R.Kind) {
case CodeCompletionResult::RK_Declaration:
case CodeCompletionResult::RK_Pattern: {
@@ -536,13 +536,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.
- llvm::Optional<std::string> UnresolvedQualifier;
+ Optional<std::string> UnresolvedQualifier;
// Construct scopes being queried in indexes.
// This method format the scopes to match the index request representation.
std::vector<std::string> scopesForIndexQuery() {
std::vector<std::string> Results;
- for (llvm::StringRef AS : AccessibleScopes) {
+ for (StringRef AS : AccessibleScopes) {
Results.push_back(AS);
if (UnresolvedQualifier)
Results.back() += *UnresolvedQualifier;
@@ -679,7 +679,7 @@ static bool isBlacklistedMember(const Na
// within the callback.
struct CompletionRecorder : public CodeCompleteConsumer {
CompletionRecorder(const CodeCompleteOptions &Opts,
- llvm::unique_function<void()> ResultsCallback)
+ unique_function<void()> ResultsCallback)
: CodeCompleteConsumer(Opts.getClangCompleteOpts(),
/*OutputIsBinary=*/false),
CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
@@ -752,7 +752,7 @@ struct CompletionRecorder : public CodeC
// Returns the filtering/sorting name for Result, which must be from Results.
// Returned string is owned by this recorder (or the AST).
- llvm::StringRef getName(const CodeCompletionResult &Result) {
+ StringRef getName(const CodeCompletionResult &Result) {
switch (Result.Kind) {
case CodeCompletionResult::RK_Declaration:
if (auto *ID = Result.Declaration->getIdentifier())
@@ -782,13 +782,13 @@ private:
CodeCompleteOptions Opts;
std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
CodeCompletionTUInfo CCTUInfo;
- llvm::unique_function<void()> ResultsCallback;
+ unique_function<void()> ResultsCallback;
};
struct ScoredSignature {
// When set, requires documentation to be requested from the index with this
// ID.
- llvm::Optional<SymbolID> IDForDoc;
+ Optional<SymbolID> IDForDoc;
SignatureInformation Signature;
SignatureQualitySignals Quality;
};
@@ -848,7 +848,7 @@ public:
// Sema does not load the docs from the preamble, so we need to fetch extra
// docs from the index instead.
- llvm::DenseMap<SymbolID, std::string> FetchedDocs;
+ DenseMap<SymbolID, std::string> FetchedDocs;
if (Index) {
LookupRequest IndexRequest;
for (const auto &S : ScoredSignatures) {
@@ -917,7 +917,7 @@ private:
// CompletionString.h.
ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
const CodeCompletionString &CCS,
- llvm::StringRef DocComment) const {
+ StringRef DocComment) const {
SignatureInformation Signature;
SignatureQualitySignals Signal;
const char *ReturnType = nullptr;
@@ -975,7 +975,7 @@ private:
Result.IDForDoc =
Result.Signature.documentation.empty() && Candidate.getFunction()
? clangd::getSymbolID(Candidate.getFunction())
- : llvm::None;
+ : None;
return Result;
}
@@ -991,7 +991,7 @@ struct SemaCompleteInput {
const PreambleData *Preamble;
StringRef Contents;
Position Pos;
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
+ IntrusiveRefCntPtr<vfs::FileSystem> VFS;
std::shared_ptr<PCHContainerOperations> PCHs;
};
@@ -1012,7 +1012,7 @@ bool semaCodeComplete(std::unique_ptr<Co
// working dirs.
}
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = Input.VFS;
+ IntrusiveRefCntPtr<vfs::FileSystem> VFS = Input.VFS;
if (Input.Preamble && Input.Preamble->StatCache)
VFS = Input.Preamble->StatCache->getConsumingFS(std::move(VFS));
IgnoreDiagnostics DummyDiagsConsumer;
@@ -1043,8 +1043,8 @@ bool semaCodeComplete(std::unique_ptr<Co
FrontendOpts.CodeCompletionAt.Column) =
offsetToClangLineColumn(Input.Contents, *Offset);
- std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
- llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
+ std::unique_ptr<MemoryBuffer> ContentsBuffer =
+ 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
@@ -1126,14 +1126,14 @@ std::future<SymbolSlab> startAsyncFuzzyF
// 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.
-llvm::Optional<FuzzyFindRequest> speculativeFuzzyFindRequestForCompletion(
+Optional<FuzzyFindRequest> speculativeFuzzyFindRequestForCompletion(
FuzzyFindRequest CachedReq, PathRef File, StringRef Content, Position Pos) {
auto Filter = speculateCompletionFilter(Content, Pos);
if (!Filter) {
elog("Failed to speculate filter text for code completion at Pos "
"{0}:{1}: {2}",
Pos.line, Pos.character, Filter.takeError());
- return llvm::None;
+ return None;
}
CachedReq.Query = *Filter;
return CachedReq;
@@ -1164,8 +1164,7 @@ clang::CodeCompleteOptions CodeCompleteO
// 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.
-llvm::SmallVector<StringRef, 1>
-getRankedIncludes(const Symbol &Sym) {
+SmallVector<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,
@@ -1174,7 +1173,7 @@ getRankedIncludes(const Symbol &Sym) {
return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
return LHS.References > RHS.References;
});
- llvm::SmallVector<StringRef, 1> Headers;
+ SmallVector<StringRef, 1> Headers;
for (const auto &Include : Includes)
Headers.push_back(Include.IncludeHeader);
return Headers;
@@ -1219,21 +1218,21 @@ 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?
- llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
+ 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.
- llvm::Optional<ScopeDistance> ScopeProximity;
+ Optional<ScopeDistance> ScopeProximity;
// 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.
- llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
- llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
+ Optional<IncludeInserter> Inserter; // Available during runWithSema.
+ 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.
- llvm::Optional<FuzzyFindRequest> SpecReq;
+ Optional<FuzzyFindRequest> SpecReq;
public:
// A CodeCompleteFlow object is only useful for calling run() exactly once.
@@ -1283,7 +1282,7 @@ public:
// The per-result proximity scoring is (amortized) very cheap.
FileDistanceOptions ProxOpts{}; // Use defaults.
const auto &SM = Recorder->CCSema->getSourceManager();
- llvm::StringMap<SourceParams> ProxSources;
+ StringMap<SourceParams> ProxSources;
for (auto &Entry : Includes.includeDepth(
SM.getFileEntryForID(SM.getMainFileID())->getName())) {
auto &Source = ProxSources[Entry.getKey()];
@@ -1302,7 +1301,7 @@ public:
getCompletionKindString(Recorder->CCContext.getKind()));
log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2})",
getCompletionKindString(Recorder->CCContext.getKind()),
- llvm::join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
+ join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
});
Recorder = RecorderOwner.get();
@@ -1422,7 +1421,7 @@ private:
const SymbolSlab &IndexResults) {
trace::Span Tracer("Merge and score results");
std::vector<CompletionCandidate::Bundle> Bundles;
- llvm::DenseMap<size_t, size_t> BundleLookup;
+ DenseMap<size_t, size_t> BundleLookup;
auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
const Symbol *IndexResult) {
CompletionCandidate C;
@@ -1441,7 +1440,7 @@ private:
Bundles.back().push_back(std::move(C));
}
};
- llvm::DenseSet<const Symbol *> UsedIndexResults;
+ DenseSet<const Symbol *> UsedIndexResults;
auto CorrespondingIndexResult =
[&](const CodeCompletionResult &SemaResult) -> const Symbol * {
if (auto SymID =
@@ -1522,8 +1521,8 @@ private:
: Scores.Quality;
dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
- llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
- llvm::to_string(Relevance));
+ to_string(Origin), Scores.Total, to_string(Quality),
+ to_string(Relevance));
NSema += bool(Origin & SymbolOrigin::AST);
NIndex += FromIndex;
@@ -1533,7 +1532,7 @@ private:
}
CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
- llvm::Optional<CodeCompletionBuilder> Builder;
+ Optional<CodeCompletionBuilder> Builder;
for (const auto &Item : Bundle) {
CodeCompletionString *SemaCCS =
Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
@@ -1549,13 +1548,12 @@ private:
}
};
-llvm::Expected<llvm::StringRef>
-speculateCompletionFilter(llvm::StringRef Content, Position Pos) {
+Expected<StringRef> speculateCompletionFilter(StringRef Content, Position Pos) {
auto Offset = positionToOffset(Content, Pos);
if (!Offset)
- return llvm::make_error<llvm::StringError>(
+ return make_error<StringError>(
"Failed to convert position to offset in content.",
- llvm::inconvertibleErrorCode());
+ inconvertibleErrorCode());
if (*Offset == 0)
return "";
@@ -1577,7 +1575,7 @@ speculateCompletionFilter(llvm::StringRe
CodeCompleteResult
codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
const PreambleData *Preamble, StringRef Contents, Position Pos,
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
+ IntrusiveRefCntPtr<vfs::FileSystem> VFS,
std::shared_ptr<PCHContainerOperations> PCHs,
CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind) {
return CodeCompleteFlow(FileName,
@@ -1590,7 +1588,7 @@ SignatureHelp signatureHelp(PathRef File
const tooling::CompileCommand &Command,
const PreambleData *Preamble, StringRef Contents,
Position Pos,
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
+ IntrusiveRefCntPtr<vfs::FileSystem> VFS,
std::shared_ptr<PCHContainerOperations> PCHs,
const SymbolIndex *Index) {
SignatureHelp Result;
@@ -1625,12 +1623,12 @@ CompletionItem CodeCompletion::render(co
LSP.label = ((InsertInclude && InsertInclude->Insertion)
? Opts.IncludeIndicator.Insert
: Opts.IncludeIndicator.NoInsert) +
- (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
+ (Opts.ShowOrigins ? "[" + to_string(Origin) + "]" : "") +
RequiredQualifier + Name + Signature;
LSP.kind = Kind;
- LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
- : ReturnType;
+ LSP.detail =
+ BundleSize > 1 ? formatv("[{0} overloads]", BundleSize) : ReturnType;
LSP.deprecated = Deprecated;
if (InsertInclude)
LSP.detail += "\n" + InsertInclude->Header;
Modified: clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp Sat Oct 20 08:30:37 2018
@@ -14,9 +14,9 @@
#include "clang/Basic/SourceManager.h"
#include <utility>
+using namespace llvm;
namespace clang {
namespace clangd {
-
namespace {
bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
@@ -24,7 +24,7 @@ bool isInformativeQualifierChunk(CodeCom
StringRef(Chunk.Text).endswith("::");
}
-void appendEscapeSnippet(const llvm::StringRef Text, std::string *Out) {
+void appendEscapeSnippet(const StringRef Text, std::string *Out) {
for (const auto Character : Text) {
if (Character == '$' || Character == '}' || Character == '\\')
Out->push_back('\\');
@@ -32,13 +32,13 @@ void appendEscapeSnippet(const llvm::Str
}
}
-bool looksLikeDocComment(llvm::StringRef CommentText) {
+bool looksLikeDocComment(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") != llvm::StringRef::npos;
+ return CommentText.find_first_not_of("/*-= \t\r\n") != StringRef::npos;
}
} // namespace
@@ -56,7 +56,7 @@ std::string getDocComment(const ASTConte
}
std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl) {
- if (llvm::isa<NamespaceDecl>(Decl)) {
+ if (isa<NamespaceDecl>(Decl)) {
// Namespaces often have too many redecls for any particular redecl comment
// to be useful. Moreover, we often confuse file headers or generated
// comments with namespace comments. Therefore we choose to just ignore
@@ -146,7 +146,7 @@ void getSignature(const CodeCompletionSt
}
std::string formatDocumentation(const CodeCompletionString &CCS,
- llvm::StringRef DocComment) {
+ StringRef DocComment) {
// Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
// information in the documentation field.
std::string Result;
Modified: clang-tools-extra/trunk/clangd/Compiler.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Compiler.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Compiler.cpp (original)
+++ clang-tools-extra/trunk/clangd/Compiler.cpp Sat Oct 20 08:30:37 2018
@@ -14,6 +14,7 @@
#include "llvm/Support/Format.h"
#include "llvm/Support/FormatVariadic.h"
+using namespace llvm;
namespace clang {
namespace clangd {
@@ -26,7 +27,7 @@ void IgnoreDiagnostics::log(DiagnosticsE
if (Info.hasSourceManager() && Info.getLocation().isValid()) {
auto &SourceMgr = Info.getSourceManager();
auto Loc = SourceMgr.getFileLoc(Info.getLocation());
- llvm::raw_svector_ostream OS(Location);
+ raw_svector_ostream OS(Location);
Loc.print(OS, SourceMgr);
OS << ":";
}
@@ -39,13 +40,11 @@ void IgnoreDiagnostics::HandleDiagnostic
IgnoreDiagnostics::log(DiagLevel, Info);
}
-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,
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
- DiagnosticConsumer &DiagsClient) {
+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) {
assert(VFS && "VFS is null");
assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
"Setting RetainRemappedFileBuffers to true will cause a memory leak "
Modified: clang-tools-extra/trunk/clangd/Diagnostics.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Diagnostics.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Diagnostics.cpp (original)
+++ clang-tools-extra/trunk/clangd/Diagnostics.cpp Sat Oct 20 08:30:37 2018
@@ -17,6 +17,7 @@
#include "llvm/Support/Path.h"
#include <algorithm>
+using namespace llvm;
namespace clang {
namespace clangd {
@@ -56,7 +57,7 @@ Range diagnosticRange(const clang::Diagn
if (locationInRange(Loc, R, M))
return halfOpenToRange(M, R);
}
- llvm::Optional<Range> FallbackRange;
+ 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);
@@ -92,7 +93,7 @@ bool isNote(DiagnosticsEngine::Level L)
return L == DiagnosticsEngine::Note || L == DiagnosticsEngine::Remark;
}
-llvm::StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
+StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
switch (Lvl) {
case DiagnosticsEngine::Ignored:
return "ignored";
@@ -121,12 +122,12 @@ llvm::StringRef diagLeveltoString(Diagno
///
/// dir1/dir2/dir3/../../dir4/header.h:12:23
/// error: undeclared identifier
-void printDiag(llvm::raw_string_ostream &OS, const DiagBase &D) {
+void printDiag(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 << llvm::sys::path::filename(D.File) << ":";
+ OS << sys::path::filename(D.File) << ":";
} else {
OS << D.File << ":";
}
@@ -146,7 +147,7 @@ void printDiag(llvm::raw_string_ostream
/// Capitalizes the first word in the diagnostic's message.
std::string capitalize(std::string Message) {
if (!Message.empty())
- Message[0] = llvm::toUpper(Message[0]);
+ Message[0] = toUpper(Message[0]);
return Message;
}
@@ -164,7 +165,7 @@ std::string capitalize(std::string Messa
/// note: candidate function not viable: requires 3 arguments
std::string mainMessage(const Diag &D) {
std::string Result;
- llvm::raw_string_ostream OS(Result);
+ raw_string_ostream OS(Result);
OS << D.Message;
for (auto &Note : D.Notes) {
OS << "\n\n";
@@ -179,7 +180,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;
- llvm::raw_string_ostream OS(Result);
+ raw_string_ostream OS(Result);
OS << Note.Message;
OS << "\n\n";
printDiag(OS, Main);
@@ -188,13 +189,13 @@ std::string noteMessage(const Diag &Main
}
} // namespace
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const DiagBase &D) {
+raw_ostream &operator<<(raw_ostream &OS, const DiagBase &D) {
if (!D.InsideMainFile)
OS << "[in " << D.File << "] ";
return OS << D.Message;
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Fix &F) {
+raw_ostream &operator<<(raw_ostream &OS, const Fix &F) {
OS << F.Message << " {";
const char *Sep = "";
for (const auto &Edit : F.Edits) {
@@ -204,7 +205,7 @@ llvm::raw_ostream &operator<<(llvm::raw_
return OS << "}";
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diag &D) {
+raw_ostream &operator<<(raw_ostream &OS, const Diag &D) {
OS << static_cast<const DiagBase &>(D);
if (!D.Notes.empty()) {
OS << ", notes: {";
@@ -226,9 +227,8 @@ llvm::raw_ostream &operator<<(llvm::raw_
return OS;
}
-void toLSPDiags(
- const Diag &D,
- llvm::function_ref<void(clangd::Diagnostic, llvm::ArrayRef<Fix>)> OutFn) {
+void toLSPDiags(const Diag &D,
+ function_ref<void(clangd::Diagnostic, ArrayRef<Fix>)> OutFn) {
auto FillBasicFields = [](const DiagBase &D) -> clangd::Diagnostic {
clangd::Diagnostic Res;
Res.range = D.Range;
@@ -248,7 +248,7 @@ void toLSPDiags(
continue;
clangd::Diagnostic Res = FillBasicFields(Note);
Res.message = noteMessage(D, Note);
- OutFn(std::move(Res), llvm::ArrayRef<Fix>());
+ OutFn(std::move(Res), ArrayRef<Fix>());
}
}
@@ -278,7 +278,7 @@ void StoreDiags::BeginSourceFile(const L
void StoreDiags::EndSourceFile() {
flushLastDiag();
- LangOpts = llvm::None;
+ LangOpts = None;
}
void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
@@ -294,7 +294,7 @@ void StoreDiags::HandleDiagnostic(Diagno
auto FillDiagBase = [&](DiagBase &D) {
D.Range = diagnosticRange(Info, *LangOpts);
- llvm::SmallString<64> Message;
+ SmallString<64> Message;
Info.FormatDiagnostic(Message);
D.Message = Message.str();
D.InsideMainFile = InsideMainFile;
@@ -312,7 +312,7 @@ void StoreDiags::HandleDiagnostic(Diagno
if (!InsideMainFile)
return false;
- llvm::SmallVector<TextEdit, 1> Edits;
+ SmallVector<TextEdit, 1> Edits;
for (auto &FixIt : Info.getFixItHints()) {
if (!isInsideMainFile(FixIt.RemoveRange.getBegin(),
Info.getSourceManager()))
@@ -320,7 +320,7 @@ void StoreDiags::HandleDiagnostic(Diagno
Edits.push_back(toTextEdit(FixIt, Info.getSourceManager(), *LangOpts));
}
- llvm::SmallString<64> Message;
+ 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);
@@ -329,7 +329,7 @@ void StoreDiags::HandleDiagnostic(Diagno
FixIt.RemoveRange, Info.getSourceManager(), *LangOpts, &Invalid);
StringRef Insert = FixIt.CodeToInsert;
if (!Invalid) {
- llvm::raw_svector_ostream M(Message);
+ raw_svector_ostream M(Message);
if (!Remove.empty() && !Insert.empty())
M << "change '" << Remove << "' to '" << Insert << "'";
else if (!Remove.empty())
Modified: clang-tools-extra/trunk/clangd/DraftStore.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/DraftStore.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/DraftStore.cpp (original)
+++ clang-tools-extra/trunk/clangd/DraftStore.cpp Sat Oct 20 08:30:37 2018
@@ -11,15 +11,16 @@
#include "SourceCode.h"
#include "llvm/Support/Errc.h"
-using namespace clang;
-using namespace clang::clangd;
+using namespace llvm;
+namespace clang {
+namespace clangd {
-llvm::Optional<std::string> DraftStore::getDraft(PathRef File) const {
+Optional<std::string> DraftStore::getDraft(PathRef File) const {
std::lock_guard<std::mutex> Lock(Mutex);
auto It = Drafts.find(File);
if (It == Drafts.end())
- return llvm::None;
+ return None;
return It->second;
}
@@ -40,13 +41,14 @@ void DraftStore::addDraft(PathRef File,
Drafts[File] = Contents;
}
-llvm::Expected<std::string> DraftStore::updateDraft(
- PathRef File, llvm::ArrayRef<TextDocumentContentChangeEvent> Changes) {
+Expected<std::string>
+DraftStore::updateDraft(PathRef File,
+ ArrayRef<TextDocumentContentChangeEvent> Changes) {
std::lock_guard<std::mutex> Lock(Mutex);
auto EntryIt = Drafts.find(File);
if (EntryIt == Drafts.end()) {
- return llvm::make_error<llvm::StringError>(
+ return make_error<StringError>(
"Trying to do incremental update on non-added document: " + File,
llvm::errc::invalid_argument);
}
@@ -60,29 +62,27 @@ llvm::Expected<std::string> DraftStore::
}
const Position &Start = Change.range->start;
- llvm::Expected<size_t> StartIndex =
- positionToOffset(Contents, Start, false);
+ Expected<size_t> StartIndex = positionToOffset(Contents, Start, false);
if (!StartIndex)
return StartIndex.takeError();
const Position &End = Change.range->end;
- llvm::Expected<size_t> EndIndex = positionToOffset(Contents, End, false);
+ Expected<size_t> EndIndex = positionToOffset(Contents, End, false);
if (!EndIndex)
return EndIndex.takeError();
if (*EndIndex < *StartIndex)
- return llvm::make_error<llvm::StringError>(
- llvm::formatv(
- "Range's end position ({0}) is before start position ({1})", End,
- Start),
+ return make_error<StringError>(
+ formatv("Range's end position ({0}) is before start position ({1})",
+ End, Start),
llvm::errc::invalid_argument);
if (Change.rangeLength &&
(ssize_t)(*EndIndex - *StartIndex) != *Change.rangeLength)
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Change's rangeLength ({0}) doesn't match the "
- "computed range length ({1}).",
- *Change.rangeLength, *EndIndex - *StartIndex),
+ return make_error<StringError>(
+ formatv("Change's rangeLength ({0}) doesn't match the "
+ "computed range length ({1}).",
+ *Change.rangeLength, *EndIndex - *StartIndex),
llvm::errc::invalid_argument);
std::string NewContents;
@@ -105,3 +105,6 @@ void DraftStore::removeDraft(PathRef Fil
Drafts.erase(File);
}
+
+} // namespace clangd
+} // namespace clang
Modified: clang-tools-extra/trunk/clangd/FS.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FS.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/FS.cpp (original)
+++ clang-tools-extra/trunk/clangd/FS.cpp Sat Oct 20 08:30:37 2018
@@ -12,16 +12,16 @@
#include "llvm/ADT/None.h"
#include "llvm/Support/Path.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-PreambleFileStatusCache::PreambleFileStatusCache(llvm::StringRef MainFilePath)
+PreambleFileStatusCache::PreambleFileStatusCache(StringRef MainFilePath)
: MainFilePath(MainFilePath) {
- assert(llvm::sys::path::is_absolute(MainFilePath));
+ assert(sys::path::is_absolute(MainFilePath));
}
-void PreambleFileStatusCache::update(const llvm::vfs::FileSystem &FS,
- llvm::vfs::Status S) {
+void PreambleFileStatusCache::update(const vfs::FileSystem &FS, vfs::Status S) {
SmallString<32> PathStore(S.getName());
if (FS.makeAbsolute(PathStore))
return;
@@ -32,26 +32,24 @@ void PreambleFileStatusCache::update(con
StatCache.insert({PathStore, std::move(S)});
}
-llvm::Optional<llvm::vfs::Status>
-PreambleFileStatusCache::lookup(llvm::StringRef File) const {
+Optional<vfs::Status> PreambleFileStatusCache::lookup(StringRef File) const {
auto I = StatCache.find(File);
if (I != StatCache.end())
return I->getValue();
- return llvm::None;
+ return None;
}
-IntrusiveRefCntPtr<llvm::vfs::FileSystem>
-PreambleFileStatusCache::getProducingFS(
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) {
+IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getProducingFS(
+ IntrusiveRefCntPtr<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 llvm::vfs::ProxyFileSystem {
+ class CollectFS : public vfs::ProxyFileSystem {
public:
- CollectFS(IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
+ CollectFS(IntrusiveRefCntPtr<vfs::FileSystem> FS,
PreambleFileStatusCache &StatCache)
: ProxyFileSystem(std::move(FS)), StatCache(StatCache) {}
- llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
+ ErrorOr<std::unique_ptr<vfs::File>>
openFileForRead(const Twine &Path) override {
auto File = getUnderlyingFS().openFileForRead(Path);
if (!File || !*File)
@@ -66,7 +64,7 @@ PreambleFileStatusCache::getProducingFS(
return File;
}
- llvm::ErrorOr<llvm::vfs::Status> status(const Twine &Path) override {
+ ErrorOr<vfs::Status> status(const Twine &Path) override {
auto S = getUnderlyingFS().status(Path);
if (S)
StatCache.update(getUnderlyingFS(), *S);
@@ -79,16 +77,15 @@ PreambleFileStatusCache::getProducingFS(
return IntrusiveRefCntPtr<CollectFS>(new CollectFS(std::move(FS), *this));
}
-IntrusiveRefCntPtr<llvm::vfs::FileSystem>
-PreambleFileStatusCache::getConsumingFS(
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) const {
- class CacheVFS : public llvm::vfs::ProxyFileSystem {
+IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getConsumingFS(
+ IntrusiveRefCntPtr<vfs::FileSystem> FS) const {
+ class CacheVFS : public vfs::ProxyFileSystem {
public:
- CacheVFS(IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
+ CacheVFS(IntrusiveRefCntPtr<vfs::FileSystem> FS,
const PreambleFileStatusCache &StatCache)
: ProxyFileSystem(std::move(FS)), StatCache(StatCache) {}
- llvm::ErrorOr<llvm::vfs::Status> status(const Twine &Path) override {
+ ErrorOr<vfs::Status> status(const Twine &Path) override {
if (auto S = StatCache.lookup(Path.str()))
return *S;
return getUnderlyingFS().status(Path);
Modified: clang-tools-extra/trunk/clangd/FileDistance.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FileDistance.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/FileDistance.cpp (original)
+++ clang-tools-extra/trunk/clangd/FileDistance.cpp Sat Oct 20 08:30:37 2018
@@ -36,9 +36,9 @@
#include "llvm/ADT/STLExtras.h"
#include <queue>
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
// Convert a path into the canonical form.
// Canonical form is either "/", or "/segment" * N:
@@ -54,12 +54,12 @@ static SmallString<128> canonicalize(Str
}
constexpr const unsigned FileDistance::Unreachable;
-const llvm::hash_code FileDistance::RootHash = hash_value(StringRef("/"));
+const hash_code FileDistance::RootHash = hash_value(StringRef("/"));
FileDistance::FileDistance(StringMap<SourceParams> Sources,
const FileDistanceOptions &Opts)
: Opts(Opts) {
- llvm::DenseMap<hash_code, SmallVector<hash_code, 4>> DownEdges;
+ DenseMap<hash_code, SmallVector<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) {
@@ -68,12 +68,12 @@ FileDistance::FileDistance(StringMap<Sou
S.second.MaxUpTraversals);
// Walk up to ancestors of this source, assigning cost.
StringRef Rest = Canonical;
- llvm::hash_code Hash = hash_value(Rest);
+ hash_code Hash = hash_value(Rest);
for (unsigned I = 0; !Rest.empty(); ++I) {
Rest = parent_path(Rest, sys::path::Style::posix);
auto NextHash = hash_value(Rest);
auto &Down = DownEdges[NextHash];
- if (!llvm::is_contained(Down, Hash))
+ if (!is_contained(Down, Hash))
Down.push_back(Hash);
// We can't just break after MaxUpTraversals, must still set DownEdges.
if (I > S.getValue().MaxUpTraversals) {
@@ -97,7 +97,7 @@ FileDistance::FileDistance(StringMap<Sou
// 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(llvm::StringRef(""))))
+ for (auto Child : DownEdges.lookup(hash_value(StringRef(""))))
Next.push(Child);
while (!Next.empty()) {
auto Parent = Next.front();
@@ -146,8 +146,8 @@ unsigned FileDistance::distance(StringRe
return Cost;
}
-unsigned URIDistance::distance(llvm::StringRef URI) {
- auto R = Cache.try_emplace(llvm::hash_value(URI), FileDistance::Unreachable);
+unsigned URIDistance::distance(StringRef URI) {
+ auto R = Cache.try_emplace(hash_value(URI), FileDistance::Unreachable);
if (!R.second)
return R.first->getSecond();
if (auto U = clangd::URI::parse(URI)) {
@@ -159,10 +159,10 @@ unsigned URIDistance::distance(llvm::Str
return R.first->second;
}
-FileDistance &URIDistance::forScheme(llvm::StringRef Scheme) {
+FileDistance &URIDistance::forScheme(StringRef Scheme) {
auto &Delegate = ByScheme[Scheme];
if (!Delegate) {
- llvm::StringMap<SourceParams> SchemeSources;
+ StringMap<SourceParams> SchemeSources;
for (const auto &Source : Sources) {
if (auto U = clangd::URI::create(Source.getKey(), Scheme))
SchemeSources.try_emplace(U->body(), Source.getValue());
@@ -176,14 +176,13 @@ FileDistance &URIDistance::forScheme(llv
return *Delegate;
}
-static std::pair<std::string, int> scopeToPath(llvm::StringRef Scope) {
+static std::pair<std::string, int> scopeToPath(StringRef Scope) {
SmallVector<StringRef, 4> Split;
Scope.split(Split, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
- return {"/" + llvm::join(Split, "/"), Split.size()};
+ return {"/" + join(Split, "/"), Split.size()};
}
-static FileDistance
-createScopeFileDistance(llvm::ArrayRef<std::string> QueryScopes) {
+static FileDistance createScopeFileDistance(ArrayRef<std::string> QueryScopes) {
FileDistanceOptions Opts;
Opts.UpCost = 2;
Opts.DownCost = 4;
@@ -210,10 +209,10 @@ createScopeFileDistance(llvm::ArrayRef<s
return FileDistance(Sources, Opts);
}
-ScopeDistance::ScopeDistance(llvm::ArrayRef<std::string> QueryScopes)
+ScopeDistance::ScopeDistance(ArrayRef<std::string> QueryScopes)
: Distance(createScopeFileDistance(QueryScopes)) {}
-unsigned ScopeDistance::distance(llvm::StringRef SymbolScope) {
+unsigned ScopeDistance::distance(StringRef SymbolScope) {
return Distance.distance(scopeToPath(SymbolScope).first);
}
Modified: clang-tools-extra/trunk/clangd/FindSymbols.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FindSymbols.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/FindSymbols.cpp (original)
+++ clang-tools-extra/trunk/clangd/FindSymbols.cpp Sat Oct 20 08:30:37 2018
@@ -23,9 +23,9 @@
#define DEBUG_TYPE "FindSymbols"
+using namespace llvm;
namespace clang {
namespace clangd {
-
namespace {
// Convert a index::SymbolKind to clangd::SymbolKind (LSP)
@@ -98,7 +98,7 @@ struct ScoredSymbolGreater {
} // namespace
-llvm::Expected<std::vector<SymbolInformation>>
+Expected<std::vector<SymbolInformation>>
getWorkspaceSymbols(StringRef Query, int Limit, const SymbolIndex *const Index,
StringRef HintPath) {
std::vector<SymbolInformation> Result;
@@ -181,7 +181,7 @@ class DocumentSymbolsConsumer : public i
ASTContext &AST;
std::vector<SymbolInformation> Symbols;
// We are always list document for the same file, so cache the value.
- llvm::Optional<URIForFile> MainFileUri;
+ Optional<URIForFile> MainFileUri;
public:
DocumentSymbolsConsumer(ASTContext &AST) : AST(AST) {}
@@ -230,7 +230,7 @@ public:
// we can get here when in the presence of "extern" decls.
return true;
}
- const NamedDecl *ND = llvm::dyn_cast<NamedDecl>(ASTNode.OrigD);
+ const NamedDecl *ND = dyn_cast<NamedDecl>(ASTNode.OrigD);
if (!shouldIncludeSymbol(ND))
return true;
@@ -262,8 +262,7 @@ public:
};
} // namespace
-llvm::Expected<std::vector<SymbolInformation>>
-getDocumentSymbols(ParsedAST &AST) {
+Expected<std::vector<SymbolInformation>> getDocumentSymbols(ParsedAST &AST) {
DocumentSymbolsConsumer DocumentSymbolsCons(AST.getASTContext());
index::IndexingOptions IndexOpts;
Modified: clang-tools-extra/trunk/clangd/FuzzyMatch.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FuzzyMatch.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/FuzzyMatch.cpp (original)
+++ clang-tools-extra/trunk/clangd/FuzzyMatch.cpp Sat Oct 20 08:30:37 2018
@@ -60,9 +60,9 @@
#include "llvm/ADT/Optional.h"
#include "llvm/Support/Format.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
constexpr int FuzzyMatcher::MaxPat;
constexpr int FuzzyMatcher::MaxWord;
@@ -299,8 +299,8 @@ int FuzzyMatcher::matchBonus(int P, int
return S;
}
-llvm::SmallString<256> FuzzyMatcher::dumpLast(llvm::raw_ostream &OS) const {
- llvm::SmallString<256> Result;
+SmallString<256> FuzzyMatcher::dumpLast(raw_ostream &OS) const {
+ SmallString<256> Result;
OS << "=== Match \"" << StringRef(Word, WordN) << "\" against ["
<< StringRef(Pat, PatN) << "] ===\n";
if (PatN == 0) {
Modified: clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp (original)
+++ clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp Sat Oct 20 08:30:37 2018
@@ -13,6 +13,7 @@
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
+using namespace llvm;
namespace clang {
namespace clangd {
@@ -21,24 +22,22 @@ GlobalCompilationDatabase::getFallbackCo
std::vector<std::string> Argv = {"clang"};
// Clang treats .h files as C by default, resulting in unhelpful diagnostics.
// Parsing as Objective C++ is friendly to more cases.
- if (llvm::sys::path::extension(File) == ".h")
+ if (sys::path::extension(File) == ".h")
Argv.push_back("-xobjective-c++-header");
Argv.push_back(File);
- return tooling::CompileCommand(llvm::sys::path::parent_path(File),
- llvm::sys::path::filename(File),
- std::move(Argv),
+ return tooling::CompileCommand(sys::path::parent_path(File),
+ sys::path::filename(File), std::move(Argv),
/*Output=*/"");
}
DirectoryBasedGlobalCompilationDatabase::
- DirectoryBasedGlobalCompilationDatabase(
- llvm::Optional<Path> CompileCommandsDir)
+ DirectoryBasedGlobalCompilationDatabase(Optional<Path> CompileCommandsDir)
: CompileCommandsDir(std::move(CompileCommandsDir)) {}
DirectoryBasedGlobalCompilationDatabase::
~DirectoryBasedGlobalCompilationDatabase() = default;
-llvm::Optional<tooling::CompileCommand>
+Optional<tooling::CompileCommand>
DirectoryBasedGlobalCompilationDatabase::getCompileCommand(PathRef File) const {
if (auto CDB = getCDBForFile(File)) {
auto Candidates = CDB->getCompileCommands(File);
@@ -49,7 +48,7 @@ DirectoryBasedGlobalCompilationDatabase:
} else {
log("Failed to find compilation database for {0}", File);
}
- return llvm::None;
+ return None;
}
tooling::CompileCommand
@@ -102,7 +101,7 @@ DirectoryBasedGlobalCompilationDatabase:
tooling::CompilationDatabase *
DirectoryBasedGlobalCompilationDatabase::getCDBForFile(PathRef File) const {
- namespace path = llvm::sys::path;
+ namespace path = sys::path;
assert((path::is_absolute(File, path::Style::posix) ||
path::is_absolute(File, path::Style::windows)) &&
"path must be absolute");
@@ -121,7 +120,7 @@ CachingCompilationDb::CachingCompilation
const GlobalCompilationDatabase &InnerCDB)
: InnerCDB(InnerCDB) {}
-llvm::Optional<tooling::CompileCommand>
+Optional<tooling::CompileCommand>
CachingCompilationDb::getCompileCommand(PathRef File) const {
std::unique_lock<std::mutex> Lock(Mut);
auto It = Cached.find(File);
@@ -129,8 +128,7 @@ CachingCompilationDb::getCompileCommand(
return It->second;
Lock.unlock();
- llvm::Optional<tooling::CompileCommand> Command =
- InnerCDB.getCompileCommand(File);
+ Optional<tooling::CompileCommand> Command = InnerCDB.getCompileCommand(File);
Lock.lock();
return Cached.try_emplace(File, std::move(Command)).first->getValue();
}
@@ -150,7 +148,7 @@ void CachingCompilationDb::clear() {
Cached.clear();
}
-llvm::Optional<tooling::CompileCommand>
+Optional<tooling::CompileCommand>
InMemoryCompilationDb::getCompileCommand(PathRef File) const {
std::lock_guard<std::mutex> Lock(Mutex);
auto It = Commands.find(File);
Modified: clang-tools-extra/trunk/clangd/Headers.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Headers.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Headers.cpp (original)
+++ clang-tools-extra/trunk/clangd/Headers.cpp Sat Oct 20 08:30:37 2018
@@ -17,6 +17,7 @@
#include "clang/Lex/HeaderSearch.h"
#include "llvm/Support/Path.h"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -29,10 +30,9 @@ public:
// Record existing #includes - both written and resolved paths. Only #includes
// in the main file are collected.
void InclusionDirective(SourceLocation HashLoc, const Token & /*IncludeTok*/,
- llvm::StringRef FileName, bool IsAngled,
+ StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange, const FileEntry *File,
- llvm::StringRef /*SearchPath*/,
- llvm::StringRef /*RelativePath*/,
+ StringRef /*SearchPath*/, StringRef /*RelativePath*/,
const Module * /*Imported*/,
SrcMgr::CharacteristicKind /*FileType*/) override {
if (SM.isInMainFile(HashLoc))
@@ -61,13 +61,13 @@ private:
} // namespace
-bool isLiteralInclude(llvm::StringRef Include) {
+bool isLiteralInclude(StringRef Include) {
return Include.startswith("<") || Include.startswith("\"");
}
bool HeaderFile::valid() const {
return (Verbatim && isLiteralInclude(File)) ||
- (!Verbatim && llvm::sys::path::is_absolute(File));
+ (!Verbatim && sys::path::is_absolute(File));
}
std::unique_ptr<PPCallbacks>
@@ -76,9 +76,9 @@ collectIncludeStructureCallback(const So
return llvm::make_unique<RecordHeaders>(SM, Out);
}
-void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
- llvm::StringRef IncludedName,
- llvm::StringRef IncludedRealName) {
+void IncludeStructure::recordInclude(StringRef IncludingName,
+ StringRef IncludedName,
+ StringRef IncludedRealName) {
auto Child = fileIndex(IncludedName);
if (!IncludedRealName.empty() && RealPathNames[Child].empty())
RealPathNames[Child] = IncludedRealName;
@@ -86,20 +86,19 @@ void IncludeStructure::recordInclude(llv
IncludeChildren[Parent].push_back(Child);
}
-unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
+unsigned IncludeStructure::fileIndex(StringRef Name) {
auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
if (R.second)
RealPathNames.emplace_back();
return R.first->getValue();
}
-llvm::StringMap<unsigned>
-IncludeStructure::includeDepth(llvm::StringRef Root) const {
+StringMap<unsigned> IncludeStructure::includeDepth(StringRef Root) const {
// Include depth 0 is the main file only.
- llvm::StringMap<unsigned> Result;
+ StringMap<unsigned> Result;
Result[Root] = 0;
std::vector<unsigned> CurrentLevel;
- llvm::DenseSet<unsigned> Seen;
+ DenseSet<unsigned> Seen;
auto It = NameToIndex.find(Root);
if (It != NameToIndex.end()) {
CurrentLevel.push_back(It->second);
@@ -139,7 +138,7 @@ bool IncludeInserter::shouldInsertInclud
assert(DeclaringHeader.valid() && InsertedHeader.valid());
if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
return false;
- auto Included = [&](llvm::StringRef Header) {
+ auto Included = [&](StringRef Header) {
return IncludedHeaders.find(Header) != IncludedHeaders.end();
};
return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
Modified: clang-tools-extra/trunk/clangd/JSONTransport.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/JSONTransport.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/JSONTransport.cpp (original)
+++ clang-tools-extra/trunk/clangd/JSONTransport.cpp Sat Oct 20 08:30:37 2018
@@ -25,7 +25,7 @@ json::Object encodeError(Error E) {
Code = L.Code;
return Error::success();
}))
- Message = llvm::toString(std::move(Unhandled));
+ Message = toString(std::move(Unhandled));
return json::Object{
{"message", std::move(Message)},
@@ -42,8 +42,8 @@ Error decodeError(const json::Object &O)
class JSONTransport : public Transport {
public:
- JSONTransport(std::FILE *In, llvm::raw_ostream &Out,
- llvm::raw_ostream *InMirror, bool Pretty, JSONStreamStyle Style)
+ JSONTransport(std::FILE *In, raw_ostream &Out, raw_ostream *InMirror,
+ bool Pretty, JSONStreamStyle Style)
: In(In), Out(Out), InMirror(InMirror ? *InMirror : nulls()),
Pretty(Pretty), Style(Style) {}
@@ -90,7 +90,7 @@ public:
} else {
// Parse error. Log the raw message.
vlog("<<< {0}\n", *JSON);
- elog("JSON parse error: {0}", llvm::toString(Doc.takeError()));
+ elog("JSON parse error: {0}", toString(Doc.takeError()));
}
}
}
@@ -99,12 +99,12 @@ public:
private:
// Dispatches incoming message to Handler onNotify/onCall/onReply.
- bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
+ bool handleMessage(json::Value Message, MessageHandler &Handler);
// Writes outgoing message to Out stream.
- void sendMessage(llvm::json::Value Message) {
+ void sendMessage(json::Value Message) {
std::string S;
- llvm::raw_string_ostream OS(S);
- OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
+ raw_string_ostream OS(S);
+ OS << formatv(Pretty ? "{0:2}" : "{0}", Message);
OS.flush();
Out << "Content-Length: " << S.size() << "\r\n\r\n" << S;
Out.flush();
@@ -112,21 +112,21 @@ private:
}
// Read raw string messages from input stream.
- llvm::Optional<std::string> readRawMessage() {
+ Optional<std::string> readRawMessage() {
return Style == JSONStreamStyle::Delimited ? readDelimitedMessage()
: readStandardMessage();
}
- llvm::Optional<std::string> readDelimitedMessage();
- llvm::Optional<std::string> readStandardMessage();
+ Optional<std::string> readDelimitedMessage();
+ Optional<std::string> readStandardMessage();
std::FILE *In;
- llvm::raw_ostream &Out;
- llvm::raw_ostream &InMirror;
+ raw_ostream &Out;
+ raw_ostream &InMirror;
bool Pretty;
JSONStreamStyle Style;
};
-bool JSONTransport::handleMessage(llvm::json::Value Message,
+bool JSONTransport::handleMessage(json::Value Message,
MessageHandler &Handler) {
// Message must be an object with "jsonrpc":"2.0".
auto *Object = Message.getAsObject();
@@ -135,7 +135,7 @@ bool JSONTransport::handleMessage(llvm::
return false;
}
// ID may be any JSON value. If absent, this is a notification.
- llvm::Optional<json::Value> ID;
+ Optional<json::Value> ID;
if (auto *I = Object->get("id"))
ID = std::move(*I);
auto Method = Object->getString("method");
@@ -172,7 +172,7 @@ bool readLine(std::FILE *In, std::string
for (;;) {
Out.resize(Size + BufSize);
// Handle EINTR which is sent when a debugger attaches on some platforms.
- if (!llvm::sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
+ if (!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 +189,17 @@ bool readLine(std::FILE *In, std::string
// Returns None when:
// - ferror() or feof() are set.
// - Content-Length is missing or empty (protocol error)
-llvm::Optional<std::string> JSONTransport::readStandardMessage() {
+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 llvm::None;
+ return None;
InMirror << Line;
- llvm::StringRef LineRef(Line);
+ StringRef LineRef(Line);
// We allow comments in headers. Technically this isn't part
@@ -214,7 +214,7 @@ llvm::Optional<std::string> JSONTranspor
"The previous value for this message ({0}) was ignored.",
ContentLength);
}
- llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
+ getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
continue;
} else if (!LineRef.trim().empty()) {
// It's another header, ignore it.
@@ -231,22 +231,22 @@ llvm::Optional<std::string> JSONTranspor
elog("Refusing to read message with long Content-Length: {0}. "
"Expect protocol errors",
ContentLength);
- return llvm::None;
+ return None;
}
if (ContentLength == 0) {
log("Warning: Missing Content-Length header, or zero-length message.");
- return llvm::None;
+ return 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 = llvm::sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
- ContentLength - Pos, In);
+ Read = 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 llvm::None;
+ return None;
}
InMirror << StringRef(&JSON[Pos], Read);
clearerr(In); // If we're done, the error was transient. If we're not done,
@@ -261,12 +261,12 @@ llvm::Optional<std::string> JSONTranspor
// - 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.
-llvm::Optional<std::string> JSONTransport::readDelimitedMessage() {
+Optional<std::string> JSONTransport::readDelimitedMessage() {
std::string JSON;
std::string Line;
while (readLine(In, Line)) {
InMirror << Line;
- auto LineRef = llvm::StringRef(Line).trim();
+ auto LineRef = StringRef(Line).trim();
if (LineRef.startswith("#")) // comment
continue;
@@ -279,17 +279,15 @@ llvm::Optional<std::string> JSONTranspor
if (ferror(In)) {
elog("Input error while reading message!");
- return llvm::None;
+ return None;
}
return std::move(JSON); // Including at EOF
}
} // namespace
-std::unique_ptr<Transport> newJSONTransport(std::FILE *In,
- llvm::raw_ostream &Out,
- llvm::raw_ostream *InMirror,
- bool Pretty,
+std::unique_ptr<Transport> newJSONTransport(std::FILE *In, raw_ostream &Out,
+ raw_ostream *InMirror, bool Pretty,
JSONStreamStyle Style) {
return llvm::make_unique<JSONTransport>(In, Out, InMirror, Pretty, Style);
}
Modified: clang-tools-extra/trunk/clangd/Logger.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Logger.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Logger.cpp (original)
+++ clang-tools-extra/trunk/clangd/Logger.cpp Sat Oct 20 08:30:37 2018
@@ -14,6 +14,7 @@
#include "llvm/Support/raw_ostream.h"
#include <mutex>
+using namespace llvm;
namespace clang {
namespace clangd {
@@ -28,14 +29,13 @@ LoggingSession::LoggingSession(clangd::L
LoggingSession::~LoggingSession() { L = nullptr; }
-void detail::log(Logger::Level Level,
- const llvm::formatv_object_base &Message) {
+void detail::log(Logger::Level Level, const formatv_object_base &Message) {
if (L)
L->log(Level, Message);
else {
static std::mutex Mu;
std::lock_guard<std::mutex> Guard(Mu);
- llvm::errs() << Message << "\n";
+ errs() << Message << "\n";
}
}
@@ -48,14 +48,14 @@ const char *detail::debugType(const char
}
void StreamLogger::log(Logger::Level Level,
- const llvm::formatv_object_base &Message) {
+ const formatv_object_base &Message) {
if (Level < MinLevel)
return;
- llvm::sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
+ sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
trace::log(Message);
std::lock_guard<std::mutex> Guard(StreamMutex);
- Logs << llvm::formatv("{0}[{1:%H:%M:%S.%L}] {2}\n", indicator(Level),
- Timestamp, Message);
+ Logs << formatv("{0}[{1:%H:%M:%S.%L}] {2}\n", indicator(Level), Timestamp,
+ Message);
Logs.flush();
}
Modified: clang-tools-extra/trunk/clangd/Protocol.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Protocol.cpp (original)
+++ clang-tools-extra/trunk/clangd/Protocol.cpp Sat Oct 20 08:30:37 2018
@@ -21,14 +21,14 @@
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
char LSPError::ID;
URIForFile::URIForFile(std::string AbsPath) {
- assert(llvm::sys::path::is_absolute(AbsPath) && "the path is relative");
+ assert(sys::path::is_absolute(AbsPath) && "the path is relative");
File = std::move(AbsPath);
}
@@ -57,7 +57,7 @@ bool fromJSON(const json::Value &E, URIF
json::Value toJSON(const URIForFile &U) { return U.uri(); }
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const URIForFile &U) {
+raw_ostream &operator<<(raw_ostream &OS, const URIForFile &U) {
return OS << U.uri();
}
@@ -82,7 +82,7 @@ json::Value toJSON(const Position &P) {
};
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Position &P) {
+raw_ostream &operator<<(raw_ostream &OS, const Position &P) {
return OS << P.line << ':' << P.character;
}
@@ -98,7 +98,7 @@ json::Value toJSON(const Range &P) {
};
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Range &R) {
+raw_ostream &operator<<(raw_ostream &OS, const Range &R) {
return OS << R.start << '-' << R.end;
}
@@ -109,7 +109,7 @@ json::Value toJSON(const Location &P) {
};
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Location &L) {
+raw_ostream &operator<<(raw_ostream &OS, const Location &L) {
return OS << L.range << '@' << L.uri;
}
@@ -139,7 +139,7 @@ json::Value toJSON(const TextEdit &P) {
};
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const TextEdit &TE) {
+raw_ostream &operator<<(raw_ostream &OS, const TextEdit &TE) {
OS << TE.range << " => \"";
printEscapedString(TE.newText, OS);
return OS << '"';
@@ -342,7 +342,7 @@ bool fromJSON(const json::Value &Params,
return O && O.map("textDocument", R.textDocument);
}
-llvm::json::Value toJSON(const Diagnostic &D) {
+json::Value toJSON(const Diagnostic &D) {
json::Object Diag{
{"range", D.range},
{"severity", D.severity},
@@ -366,7 +366,7 @@ bool fromJSON(const json::Value &Params,
return O && O.map("diagnostics", R.diagnostics);
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diagnostic &D) {
+raw_ostream &operator<<(raw_ostream &OS, const Diagnostic &D) {
OS << D.range << " [";
switch (D.severity) {
case 1:
@@ -399,7 +399,7 @@ bool fromJSON(const json::Value &Params,
return O && O.map("changes", R.changes);
}
-const llvm::StringLiteral ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND =
+const StringLiteral ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND =
"clangd.applyFix";
bool fromJSON(const json::Value &Params, ExecuteCommandParams &R) {
json::ObjectMapper O(Params);
@@ -423,8 +423,7 @@ json::Value toJSON(const SymbolInformati
};
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
- const SymbolInformation &SI) {
+raw_ostream &operator<<(raw_ostream &O, const SymbolInformation &SI) {
O << SI.containerName << "::" << SI.name << " - " << toJSON(SI);
return O;
}
@@ -441,9 +440,9 @@ json::Value toJSON(const Command &C) {
return std::move(Cmd);
}
-const llvm::StringLiteral CodeAction::QUICKFIX_KIND = "quickfix";
+const StringLiteral CodeAction::QUICKFIX_KIND = "quickfix";
-llvm::json::Value toJSON(const CodeAction &CA) {
+json::Value toJSON(const CodeAction &CA) {
auto CodeAction = json::Object{{"title", CA.title}};
if (CA.kind)
CodeAction["kind"] = *CA.kind;
@@ -575,7 +574,7 @@ json::Value toJSON(const CompletionItem
return std::move(Result);
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const CompletionItem &I) {
+raw_ostream &operator<<(raw_ostream &O, const CompletionItem &I) {
O << I.label << " - " << toJSON(I);
return O;
}
@@ -611,8 +610,7 @@ json::Value toJSON(const SignatureInform
return std::move(Result);
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
- const SignatureInformation &I) {
+raw_ostream &operator<<(raw_ostream &O, const SignatureInformation &I) {
O << I.label << " - " << toJSON(I);
return O;
}
@@ -642,8 +640,7 @@ json::Value toJSON(const DocumentHighlig
};
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
- const DocumentHighlight &V) {
+raw_ostream &operator<<(raw_ostream &O, const DocumentHighlight &V) {
O << V.range;
if (V.kind == DocumentHighlightKind::Read)
O << "(r)";
@@ -657,8 +654,7 @@ bool fromJSON(const json::Value &Params,
return O && O.map("settings", CCP.settings);
}
-bool fromJSON(const llvm::json::Value &Params,
- ClangdCompileCommand &CDbUpdate) {
+bool fromJSON(const json::Value &Params, ClangdCompileCommand &CDbUpdate) {
json::ObjectMapper O(Params);
return O && O.map("workingDirectory", CDbUpdate.workingDirectory) &&
O.map("compilationCommand", CDbUpdate.compilationCommand);
Modified: clang-tools-extra/trunk/clangd/Quality.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Quality.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Quality.cpp (original)
+++ clang-tools-extra/trunk/clangd/Quality.cpp Sat Oct 20 08:30:37 2018
@@ -31,9 +31,9 @@
#include <algorithm>
#include <cmath>
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
static bool isReserved(StringRef Name) {
// FIXME: Should we exclude _Bool and others recognized by the standard?
return Name.size() >= 2 && Name[0] == '_' &&
@@ -308,7 +308,7 @@ void SymbolRelevanceSignals::merge(const
NeedsFixIts = !SemaCCResult.FixIts.empty();
}
-static std::pair<float, unsigned> uriProximity(llvm::StringRef SymbolURI,
+static std::pair<float, unsigned> uriProximity(StringRef SymbolURI,
URIDistance *D) {
if (!D || SymbolURI.empty())
return {0.f, 0u};
@@ -318,7 +318,7 @@ static std::pair<float, unsigned> uriPro
}
static float scopeBoost(ScopeDistance &Distance,
- llvm::Optional<llvm::StringRef> SymbolScope) {
+ Optional<StringRef> SymbolScope) {
if (!SymbolScope)
return 1;
auto D = Distance.distance(*SymbolScope);
@@ -429,20 +429,19 @@ static uint32_t encodeFloat(float F) {
return U + TopBit; // Positive floats map onto the high half of integers.
}
-std::string sortText(float Score, llvm::StringRef Name) {
+std::string sortText(float Score, StringRef Name) {
// We convert -Score to an integer, and hex-encode for readability.
// Example: [0.5, "foo"] -> "41000000foo"
std::string S;
- llvm::raw_string_ostream OS(S);
- write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower,
+ raw_string_ostream OS(S);
+ write_hex(OS, encodeFloat(-Score), HexPrintStyle::Lower,
/*Width=*/2 * sizeof(Score));
OS << Name;
OS.flush();
return S;
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
- const SignatureQualitySignals &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",
Modified: clang-tools-extra/trunk/clangd/RIFF.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/RIFF.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/RIFF.cpp (original)
+++ clang-tools-extra/trunk/clangd/RIFF.cpp Sat Oct 20 08:30:37 2018
@@ -42,7 +42,7 @@ Expected<Chunk> readChunk(StringRef &Str
raw_ostream &operator<<(raw_ostream &OS, const Chunk &C) {
OS.write(C.ID.data(), C.ID.size());
char Size[4];
- llvm::support::endian::write32le(Size, C.Data.size());
+ support::endian::write32le(Size, C.Data.size());
OS.write(Size, sizeof(Size));
OS << C.Data;
if (C.Data.size() % 2)
@@ -50,7 +50,7 @@ raw_ostream &operator<<(raw_ostream &OS,
return OS;
}
-llvm::Expected<File> readFile(llvm::StringRef Stream) {
+Expected<File> readFile(StringRef Stream) {
auto RIFF = readChunk(Stream);
if (!RIFF)
return RIFF.takeError();
@@ -60,7 +60,7 @@ llvm::Expected<File> readFile(llvm::Stri
return makeError("RIFF chunk too short");
File F;
std::copy(RIFF->Data.begin(), RIFF->Data.begin() + 4, F.Type.begin());
- for (llvm::StringRef Body = RIFF->Data.drop_front(4); !Body.empty();)
+ for (StringRef Body = RIFF->Data.drop_front(4); !Body.empty();)
if (auto Chunk = readChunk(Body)) {
F.Chunks.push_back(*Chunk);
} else
@@ -75,7 +75,7 @@ raw_ostream &operator<<(raw_ostream &OS,
DataLen += 4 + 4 + C.Data.size() + (C.Data.size() % 2);
OS << "RIFF";
char Size[4];
- llvm::support::endian::write32le(Size, DataLen);
+ support::endian::write32le(Size, DataLen);
OS.write(Size, sizeof(Size));
OS.write(F.Type.data(), F.Type.size());
for (const auto &C : F.Chunks)
Modified: clang-tools-extra/trunk/clangd/SourceCode.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/SourceCode.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/SourceCode.cpp (original)
+++ clang-tools-extra/trunk/clangd/SourceCode.cpp Sat Oct 20 08:30:37 2018
@@ -16,9 +16,9 @@
#include "llvm/Support/Error.h"
#include "llvm/Support/Path.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
// Here be dragons. LSP positions use columns measured in *UTF-16 code units*!
// Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial.
@@ -80,23 +80,23 @@ static size_t utf16Len(StringRef U8) {
return Count;
}
-llvm::Expected<size_t> positionToOffset(StringRef Code, Position P,
- bool AllowColumnsBeyondLineLength) {
+Expected<size_t> positionToOffset(StringRef Code, Position P,
+ bool AllowColumnsBeyondLineLength) {
if (P.line < 0)
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Line value can't be negative ({0})", P.line),
- llvm::errc::invalid_argument);
+ return make_error<StringError>(
+ formatv("Line value can't be negative ({0})", P.line),
+ errc::invalid_argument);
if (P.character < 0)
- return llvm::make_error<llvm::StringError>(
- llvm::formatv("Character value can't be negative ({0})", P.character),
- llvm::errc::invalid_argument);
+ return make_error<StringError>(
+ formatv("Character value can't be negative ({0})", P.character),
+ 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 llvm::make_error<llvm::StringError>(
- llvm::formatv("Line value is out of range ({0})", P.line),
- llvm::errc::invalid_argument);
+ return make_error<StringError>(
+ formatv("Line value is out of range ({0})", P.line),
+ errc::invalid_argument);
StartOfLine = NextNL + 1;
}
@@ -108,10 +108,10 @@ llvm::Expected<size_t> positionToOffset(
size_t ByteOffsetInLine = measureUTF16(
Code.substr(StartOfLine, NextNL - StartOfLine), P.character, Valid);
if (!Valid && !AllowColumnsBeyondLineLength)
- 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 make_error<StringError>(
+ formatv("UTF-16 offset {0} is invalid for line {1}", P.character,
+ P.line),
+ errc::invalid_argument);
return StartOfLine + ByteOffsetInLine;
}
@@ -162,10 +162,9 @@ std::pair<size_t, size_t> offsetToClangL
return {Lines + 1, Offset - StartOfLine + 1};
}
-std::pair<llvm::StringRef, llvm::StringRef>
-splitQualifiedName(llvm::StringRef QName) {
+std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
size_t Pos = QName.rfind("::");
- if (Pos == llvm::StringRef::npos)
+ if (Pos == StringRef::npos)
return {StringRef(), QName};
return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
}
@@ -185,8 +184,8 @@ std::vector<TextEdit> replacementsToEdit
return Edits;
}
-llvm::Optional<std::string> getRealPath(const FileEntry *F,
- const SourceManager &SourceMgr) {
+Optional<std::string> getRealPath(const FileEntry *F,
+ const SourceManager &SourceMgr) {
// Ideally, we get the real path from the FileEntry object.
SmallString<128> FilePath = F->tryGetRealPathName();
if (!FilePath.empty()) {
@@ -196,16 +195,16 @@ llvm::Optional<std::string> getRealPath(
// Otherwise, we try to compute ourselves.
vlog("FileEntry for {0} did not contain the real path.", F->getName());
- llvm::SmallString<128> Path = F->getName();
+ SmallString<128> Path = F->getName();
- if (!llvm::sys::path::is_absolute(Path)) {
+ if (!sys::path::is_absolute(Path)) {
if (!SourceMgr.getFileManager().makeAbsolutePath(Path)) {
log("Could not turn relative path to absolute: {0}", Path);
- return llvm::None;
+ return None;
}
}
- llvm::SmallString<128> RealPath;
+ SmallString<128> RealPath;
if (SourceMgr.getFileManager().getVirtualFileSystem()->getRealPath(
Path, RealPath)) {
log("Could not compute real path: {0}", Path);
Modified: clang-tools-extra/trunk/clangd/TUScheduler.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/TUScheduler.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/TUScheduler.cpp (original)
+++ clang-tools-extra/trunk/clangd/TUScheduler.cpp Sat Oct 20 08:30:37 2018
@@ -55,6 +55,7 @@
#include <queue>
#include <thread>
+using namespace llvm;
namespace clang {
namespace clangd {
using std::chrono::steady_clock;
@@ -65,10 +66,10 @@ class ASTWorker;
static clang::clangd::Key<std::string> kFileBeingProcessed;
-llvm::Optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
+Optional<StringRef> TUScheduler::getFileBeingProcessedInContext() {
if (auto *File = Context::current().get(kFileBeingProcessed))
return StringRef(*File);
- return llvm::None;
+ return None;
}
/// An LRU cache of idle ASTs.
@@ -111,17 +112,17 @@ 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.
- llvm::Optional<std::unique_ptr<ParsedAST>> take(Key K) {
+ Optional<std::unique_ptr<ParsedAST>> take(Key K) {
std::unique_lock<std::mutex> Lock(Mut);
auto Existing = findByKey(K);
if (Existing == LRU.end())
- return llvm::None;
+ return None;
std::unique_ptr<ParsedAST> V = std::move(Existing->second);
LRU.erase(Existing);
// 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 llvm::Optional<std::unique_ptr<ParsedAST>>(std::move(V));
+ return Optional<std::unique_ptr<ParsedAST>>(std::move(V));
}
private:
@@ -176,16 +177,15 @@ public:
void update(ParseInputs Inputs, WantDiagnostics,
llvm::unique_function<void(std::vector<Diag>)> OnUpdated);
- void
- runWithAST(llvm::StringRef Name,
- llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action);
+ void runWithAST(StringRef Name,
+ unique_function<void(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(
- llvm::unique_function<void(std::shared_ptr<const PreambleData>)>);
+ 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(llvm::StringRef Name, llvm::unique_function<void()> Task,
- llvm::Optional<WantDiagnostics> UpdateType);
+ void startTask(StringRef Name, unique_function<void()> Task,
+ Optional<WantDiagnostics> UpdateType);
/// Determines the next action to perform.
/// All actions that should never run are discarded.
/// Returns a deadline for the next action. If it's expired, run now.
@@ -214,11 +214,11 @@ private:
bool shouldSkipHeadLocked() const;
struct Request {
- llvm::unique_function<void()> Action;
+ unique_function<void()> Action;
std::string Name;
steady_clock::time_point AddTime;
Context Ctx;
- llvm::Optional<WantDiagnostics> UpdateType;
+ Optional<WantDiagnostics> UpdateType;
};
/// Handles retention of ASTs.
@@ -306,7 +306,7 @@ ASTWorkerHandle ASTWorker::create(PathRe
FileName, IdleASTs, Barrier, /*RunSync=*/!Tasks, UpdateDebounce,
std::move(PCHs), StorePreamblesInMemory, Callbacks));
if (Tasks)
- Tasks->runAsync("worker:" + llvm::sys::path::filename(FileName),
+ Tasks->runAsync("worker:" + sys::path::filename(FileName),
[Worker]() { Worker->run(); });
return ASTWorkerHandle(std::move(Worker));
@@ -332,9 +332,8 @@ ASTWorker::~ASTWorker() {
#endif
}
-void ASTWorker::update(
- ParseInputs Inputs, WantDiagnostics WantDiags,
- llvm::unique_function<void(std::vector<Diag>)> OnUpdated) {
+void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags,
+ unique_function<void(std::vector<Diag>)> OnUpdated) {
auto Task = [=](decltype(OnUpdated) OnUpdated) mutable {
// Will be used to check if we can avoid rebuilding the AST.
bool InputsAreTheSame =
@@ -348,7 +347,7 @@ void ASTWorker::update(
log("Updating file {0} with command [{1}] {2}", FileName,
Inputs.CompileCommand.Directory,
- llvm::join(Inputs.CompileCommand.CommandLine, " "));
+ join(Inputs.CompileCommand.CommandLine, " "));
// Rebuild the preamble and the AST.
std::unique_ptr<CompilerInvocation> Invocation =
buildCompilerInvocation(Inputs);
@@ -407,9 +406,9 @@ void ASTWorker::update(
return;
// Get the AST for diagnostics.
- llvm::Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
+ Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
if (!AST) {
- llvm::Optional<ParsedAST> NewAST =
+ Optional<ParsedAST> NewAST =
buildAST(FileName, std::move(Invocation), Inputs, NewPreamble, PCHs);
AST = NewAST ? llvm::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
}
@@ -431,33 +430,32 @@ void ASTWorker::update(
}
void ASTWorker::runWithAST(
- llvm::StringRef Name,
- llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action) {
+ StringRef Name, unique_function<void(Expected<InputsAndAST>)> Action) {
auto Task = [=](decltype(Action) Action) {
- llvm::Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
+ Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
if (!AST) {
std::unique_ptr<CompilerInvocation> Invocation =
buildCompilerInvocation(FileInputs);
// Try rebuilding the AST.
- llvm::Optional<ParsedAST> NewAST =
+ Optional<ParsedAST> NewAST =
Invocation
? buildAST(FileName,
llvm::make_unique<CompilerInvocation>(*Invocation),
FileInputs, getPossiblyStalePreamble(), PCHs)
- : llvm::None;
+ : None;
AST = NewAST ? llvm::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
}
// Make sure we put the AST back into the LRU cache.
- auto _ = llvm::make_scope_exit(
+ auto _ = make_scope_exit(
[&AST, this]() { IdleASTs.put(this, std::move(*AST)); });
// Run the user-provided action.
if (!*AST)
- return Action(llvm::make_error<llvm::StringError>(
- "invalid AST", llvm::errc::invalid_argument));
+ return Action(
+ make_error<StringError>("invalid AST", errc::invalid_argument));
Action(InputsAndAST{FileInputs, **AST});
};
startTask(Name, Bind(Task, std::move(Action)),
- /*UpdateType=*/llvm::None);
+ /*UpdateType=*/None);
}
std::shared_ptr<const PreambleData>
@@ -467,7 +465,7 @@ ASTWorker::getPossiblyStalePreamble() co
}
void ASTWorker::getCurrentPreamble(
- llvm::unique_function<void(std::shared_ptr<const PreambleData>)> Callback) {
+ 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.
@@ -489,7 +487,7 @@ void ASTWorker::getCurrentPreamble(
std::move(Callback)),
"GetPreamble", steady_clock::now(),
Context::current().clone(),
- /*UpdateType=*/llvm::None});
+ /*UpdateType=*/None});
Lock.unlock();
RequestsCV.notify_all();
}
@@ -519,12 +517,11 @@ void ASTWorker::stop() {
RequestsCV.notify_all();
}
-void ASTWorker::startTask(llvm::StringRef Name,
- llvm::unique_function<void()> Task,
- llvm::Optional<WantDiagnostics> UpdateType) {
+void ASTWorker::startTask(StringRef Name, unique_function<void()> Task,
+ Optional<WantDiagnostics> UpdateType) {
if (RunSync) {
assert(!Done && "running a task after stop()");
- trace::Span Tracer(Name + ":" + llvm::sys::path::filename(FileName));
+ trace::Span Tracer(Name + ":" + sys::path::filename(FileName));
Task();
return;
}
@@ -698,9 +695,9 @@ bool TUScheduler::blockUntilIdle(Deadlin
return true;
}
-void TUScheduler::update(
- PathRef File, ParseInputs Inputs, WantDiagnostics WantDiags,
- llvm::unique_function<void(std::vector<Diag>)> OnUpdated) {
+void TUScheduler::update(PathRef File, ParseInputs Inputs,
+ WantDiagnostics WantDiags,
+ unique_function<void(std::vector<Diag>)> OnUpdated) {
std::unique_ptr<FileData> &FD = Files[File];
if (!FD) {
// Create a new worker to process the AST-related tasks.
@@ -724,12 +721,12 @@ void TUScheduler::remove(PathRef File) {
}
void TUScheduler::runWithAST(
- llvm::StringRef Name, PathRef File,
- llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action) {
+ StringRef Name, PathRef File,
+ unique_function<void(Expected<InputsAndAST>)> Action) {
auto It = Files.find(File);
if (It == Files.end()) {
- Action(llvm::make_error<LSPError>(
- "trying to get AST for non-added document", ErrorCode::InvalidParams));
+ Action(make_error<LSPError>("trying to get AST for non-added document",
+ ErrorCode::InvalidParams));
return;
}
@@ -737,13 +734,12 @@ void TUScheduler::runWithAST(
}
void TUScheduler::runWithPreamble(
- llvm::StringRef Name, PathRef File, PreambleConsistency Consistency,
- llvm::unique_function<void(llvm::Expected<InputsAndPreamble>)> Action) {
+ StringRef Name, PathRef File, PreambleConsistency Consistency,
+ unique_function<void(Expected<InputsAndPreamble>)> Action) {
auto It = Files.find(File);
if (It == Files.end()) {
- Action(llvm::make_error<LSPError>(
- "trying to get preamble for non-added document",
- ErrorCode::InvalidParams));
+ Action(make_error<LSPError>("trying to get preamble for non-added document",
+ ErrorCode::InvalidParams));
return;
}
@@ -795,7 +791,7 @@ void TUScheduler::runWithPreamble(
};
PreambleTasks->runAsync(
- "task:" + llvm::sys::path::filename(File),
+ "task:" + sys::path::filename(File),
Bind(Task, std::string(Name), std::string(File), It->second->Contents,
It->second->Command,
Context::current().derive(kFileBeingProcessed, File),
Modified: clang-tools-extra/trunk/clangd/Threading.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Threading.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Threading.cpp (original)
+++ clang-tools-extra/trunk/clangd/Threading.cpp Sat Oct 20 08:30:37 2018
@@ -5,6 +5,7 @@
#include "llvm/Support/Threading.h"
#include <thread>
+using namespace llvm;
namespace clang {
namespace clangd {
@@ -50,14 +51,14 @@ bool AsyncTaskRunner::wait(Deadline D) c
[&] { return InFlightTasks == 0; });
}
-void AsyncTaskRunner::runAsync(const llvm::Twine &Name,
- llvm::unique_function<void()> Action) {
+void AsyncTaskRunner::runAsync(const Twine &Name,
+ unique_function<void()> Action) {
{
std::lock_guard<std::mutex> Lock(Mutex);
++InFlightTasks;
}
- auto CleanupTask = llvm::make_scope_exit([this]() {
+ auto CleanupTask = make_scope_exit([this]() {
std::lock_guard<std::mutex> Lock(Mutex);
int NewTasksCnt = --InFlightTasks;
if (NewTasksCnt == 0) {
@@ -69,7 +70,7 @@ void AsyncTaskRunner::runAsync(const llv
std::thread(
[](std::string Name, decltype(Action) Action, decltype(CleanupTask)) {
- llvm::set_thread_name(Name);
+ set_thread_name(Name);
Action();
// Make sure function stored by Action is destroyed before CleanupTask
// is run.
@@ -79,7 +80,7 @@ void AsyncTaskRunner::runAsync(const llv
.detach();
}
-Deadline timeoutSeconds(llvm::Optional<double> Seconds) {
+Deadline timeoutSeconds(Optional<double> Seconds) {
using namespace std::chrono;
if (!Seconds)
return Deadline::infinity();
Modified: clang-tools-extra/trunk/clangd/Trace.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Trace.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Trace.cpp (original)
+++ clang-tools-extra/trunk/clangd/Trace.cpp Sat Oct 20 08:30:37 2018
@@ -19,10 +19,10 @@
#include <atomic>
#include <mutex>
+using namespace llvm;
namespace clang {
namespace clangd {
namespace trace {
-using namespace llvm;
namespace {
// The current implementation is naive: each thread writes to Out guarded by Mu.
@@ -49,7 +49,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(llvm::StringRef Name, json::Object *Args) override {
+ Context beginSpan(StringRef Name, json::Object *Args) override {
return Context::current().derive(
SpanKey, llvm::make_unique<JSONSpan>(this, Name, Args));
}
@@ -62,7 +62,7 @@ public:
Context::current().getExisting(SpanKey)->markEnded();
}
- void instant(llvm::StringRef Name, json::Object &&Args) override {
+ void instant(StringRef Name, json::Object &&Args) override {
captureThreadMetadata();
jsonEvent("i", json::Object{{"name", Name}, {"args", std::move(Args)}});
}
@@ -80,7 +80,7 @@ public:
private:
class JSONSpan {
public:
- JSONSpan(JSONTracer *Tracer, llvm::StringRef Name, json::Object *Args)
+ JSONSpan(JSONTracer *Tracer, StringRef Name, json::Object *Args)
: StartTime(Tracer->timestamp()), EndTime(0), Name(Name),
TID(get_threadid()), Tracer(Tracer), Args(Args) {
// ~JSONSpan() may run in a different thread, so we need to capture now.
@@ -195,8 +195,7 @@ Session::Session(EventTracer &Tracer) {
Session::~Session() { T = nullptr; }
-std::unique_ptr<EventTracer> createJSONTracer(llvm::raw_ostream &OS,
- bool Pretty) {
+std::unique_ptr<EventTracer> createJSONTracer(raw_ostream &OS, bool Pretty) {
return llvm::make_unique<JSONTracer>(OS, Pretty);
}
@@ -207,19 +206,19 @@ void log(const Twine &Message) {
}
// Returned context owns Args.
-static Context makeSpanContext(llvm::Twine Name, json::Object *Args) {
+static Context makeSpanContext(Twine Name, json::Object *Args) {
if (!T)
return Context::current().clone();
WithContextValue WithArgs{std::unique_ptr<json::Object>(Args)};
return T->beginSpan(Name.isSingleStringRef() ? Name.getSingleStringRef()
- : llvm::StringRef(Name.str()),
+ : 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(llvm::Twine Name)
+Span::Span(Twine Name)
: Args(T ? new json::Object() : nullptr),
RestoreCtx(makeSpanContext(Name, Args)) {}
Modified: clang-tools-extra/trunk/clangd/URI.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/URI.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/URI.cpp (original)
+++ clang-tools-extra/trunk/clangd/URI.cpp Sat Oct 20 08:30:37 2018
@@ -20,13 +20,13 @@
LLVM_INSTANTIATE_REGISTRY(clang::clangd::URISchemeRegistry)
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
-inline llvm::Error make_string_error(const llvm::Twine &Message) {
- return llvm::make_error<llvm::StringError>(Message,
- llvm::inconvertibleErrorCode());
+inline Error make_string_error(const Twine &Message) {
+ return make_error<StringError>(Message, inconvertibleErrorCode());
}
/// \brief This manages file paths in the file system. All paths in the scheme
@@ -35,9 +35,8 @@ class FileSystemScheme : public URISchem
public:
static const char *Scheme;
- llvm::Expected<std::string>
- getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
- llvm::StringRef /*HintPath*/) const override {
+ Expected<std::string> getAbsolutePath(StringRef /*Authority*/, StringRef Body,
+ StringRef /*HintPath*/) const override {
if (!Body.startswith("/"))
return make_string_error("File scheme: expect body to be an absolute "
"path starting with '/': " +
@@ -45,13 +44,12 @@ public:
// For Windows paths e.g. /X:
if (Body.size() > 2 && Body[0] == '/' && Body[2] == ':')
Body.consume_front("/");
- llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
- llvm::sys::path::native(Path);
+ SmallVector<char, 16> Path(Body.begin(), Body.end());
+ sys::path::native(Path);
return std::string(Path.begin(), Path.end());
}
- llvm::Expected<URI>
- uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
+ Expected<URI> uriFromAbsolutePath(StringRef AbsolutePath) const override {
using namespace llvm::sys;
std::string Body;
@@ -69,8 +67,7 @@ static URISchemeRegistry::Add<FileSystem
X(FileSystemScheme::Scheme,
"URI scheme for absolute paths in the file system.");
-llvm::Expected<std::unique_ptr<URIScheme>>
-findSchemeByName(llvm::StringRef Scheme) {
+Expected<std::unique_ptr<URIScheme>> findSchemeByName(StringRef Scheme) {
for (auto I = URISchemeRegistry::begin(), E = URISchemeRegistry::end();
I != E; ++I) {
if (I->getName() != Scheme)
@@ -102,12 +99,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(llvm::StringRef Content) {
+std::string percentEncode(StringRef Content) {
std::string Result;
- llvm::raw_string_ostream OS(Result);
+ raw_string_ostream OS(Result);
for (unsigned char C : Content)
if (shouldEscape(C))
- OS << '%' << llvm::format_hex_no_prefix(C, 2, /*Upper = */true);
+ OS << '%' << format_hex_no_prefix(C, 2, /*Upper = */ true);
else
OS << C;
@@ -116,16 +113,16 @@ std::string percentEncode(llvm::StringRe
}
/// Decodes a string according to percent-encoding.
-std::string percentDecode(llvm::StringRef Content) {
+std::string percentDecode(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() && llvm::isHexDigit(*(I + 1)) &&
- llvm::isHexDigit(*(I + 2))) {
- Result.push_back(llvm::hexFromNibbles(*(I + 1), *(I + 2)));
+ if (*I == '%' && I + 2 < Content.end() && isHexDigit(*(I + 1)) &&
+ isHexDigit(*(I + 2))) {
+ Result.push_back(hexFromNibbles(*(I + 1), *(I + 2)));
I += 2;
} else
Result.push_back(*I);
@@ -133,20 +130,19 @@ std::string percentDecode(llvm::StringRe
return Result;
}
-bool isValidScheme(llvm::StringRef Scheme) {
+bool isValidScheme(StringRef Scheme) {
if (Scheme.empty())
return false;
- if (!llvm::isAlpha(Scheme[0]))
+ if (!isAlpha(Scheme[0]))
return false;
return std::all_of(Scheme.begin() + 1, Scheme.end(), [](char C) {
- return llvm::isAlnum(C) || C == '+' || C == '.' || C == '-';
+ return isAlnum(C) || C == '+' || C == '.' || C == '-';
});
}
} // namespace
-URI::URI(llvm::StringRef Scheme, llvm::StringRef Authority,
- llvm::StringRef Body)
+URI::URI(StringRef Scheme, StringRef Authority, StringRef Body)
: Scheme(Scheme), Authority(Authority), Body(Body) {
assert(!Scheme.empty());
assert((Authority.empty() || Body.startswith("/")) &&
@@ -155,31 +151,31 @@ URI::URI(llvm::StringRef Scheme, llvm::S
std::string URI::toString() const {
std::string Result;
- llvm::raw_string_ostream OS(Result);
+ 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() || llvm::StringRef(Body).startswith("/"))
+ if (!Authority.empty() || StringRef(Body).startswith("/"))
OS << "//" << percentEncode(Authority);
OS << percentEncode(Body);
OS.flush();
return Result;
}
-llvm::Expected<URI> URI::parse(llvm::StringRef OrigUri) {
+Expected<URI> URI::parse(StringRef OrigUri) {
URI U;
- llvm::StringRef Uri = OrigUri;
+ StringRef Uri = OrigUri;
auto Pos = Uri.find(':');
- if (Pos == llvm::StringRef::npos)
+ if (Pos == 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(llvm::formatv("Invalid scheme: {0} (decoded: {1})",
- SchemeStr, U.Scheme));
+ return make_string_error(
+ formatv("Invalid scheme: {0} (decoded: {1})", SchemeStr, U.Scheme));
Uri = Uri.substr(Pos + 1);
if (Uri.consume_front("//")) {
Pos = Uri.find('/');
@@ -190,9 +186,8 @@ llvm::Expected<URI> URI::parse(llvm::Str
return U;
}
-llvm::Expected<URI> URI::create(llvm::StringRef AbsolutePath,
- llvm::StringRef Scheme) {
- if (!llvm::sys::path::is_absolute(AbsolutePath))
+Expected<URI> URI::create(StringRef AbsolutePath, StringRef Scheme) {
+ if (!sys::path::is_absolute(AbsolutePath))
return make_string_error("Not a valid absolute path: " + AbsolutePath);
auto S = findSchemeByName(Scheme);
if (!S)
@@ -200,9 +195,9 @@ llvm::Expected<URI> URI::create(llvm::St
return S->get()->uriFromAbsolutePath(AbsolutePath);
}
-llvm::Expected<URI> URI::create(llvm::StringRef AbsolutePath,
- const std::vector<std::string> &Schemes) {
- if (!llvm::sys::path::is_absolute(AbsolutePath))
+Expected<URI> URI::create(StringRef AbsolutePath,
+ const std::vector<std::string> &Schemes) {
+ if (!sys::path::is_absolute(AbsolutePath))
return make_string_error("Not a valid absolute path: " + AbsolutePath);
for (const auto &Scheme : Schemes) {
auto URI = URI::create(AbsolutePath, Scheme);
@@ -210,32 +205,30 @@ llvm::Expected<URI> URI::create(llvm::St
// should be just skipped.
if (!URI) {
// Ignore the error.
- llvm::consumeError(URI.takeError());
+ consumeError(URI.takeError());
continue;
}
return URI;
}
- return make_string_error(
- "Couldn't convert " + AbsolutePath +
- " to any given scheme: " + llvm::join(Schemes, ", "));
+ return make_string_error("Couldn't convert " + AbsolutePath +
+ " to any given scheme: " + join(Schemes, ", "));
}
-URI URI::createFile(llvm::StringRef AbsolutePath) {
+URI URI::createFile(StringRef AbsolutePath) {
auto U = create(AbsolutePath, "file");
if (!U)
llvm_unreachable(llvm::toString(U.takeError()).c_str());
return std::move(*U);
}
-llvm::Expected<std::string> URI::resolve(const URI &Uri,
- llvm::StringRef HintPath) {
+Expected<std::string> URI::resolve(const URI &Uri, StringRef HintPath) {
auto S = findSchemeByName(Uri.Scheme);
if (!S)
return S.takeError();
return S->get()->getAbsolutePath(Uri.Authority, Uri.Body, HintPath);
}
-llvm::Expected<std::string> URI::includeSpelling(const URI &Uri) {
+Expected<std::string> URI::includeSpelling(const URI &Uri) {
auto S = findSchemeByName(Uri.Scheme);
if (!S)
return S.takeError();
Modified: clang-tools-extra/trunk/clangd/XRefs.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/XRefs.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/XRefs.cpp (original)
+++ clang-tools-extra/trunk/clangd/XRefs.cpp Sat Oct 20 08:30:37 2018
@@ -18,9 +18,9 @@
#include "clang/Index/USRGeneration.h"
#include "llvm/Support/Path.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
namespace {
// Get the definition from a given declaration `D`.
@@ -46,19 +46,19 @@ void logIfOverflow(const SymbolLocation
// HintPath is used to resolve the path of URI.
// FIXME: figure out a good home for it, and share the implementation with
// FindSymbols.
-llvm::Optional<Location> toLSPLocation(const SymbolLocation &Loc,
- llvm::StringRef HintPath) {
+Optional<Location> toLSPLocation(const SymbolLocation &Loc,
+ StringRef HintPath) {
if (!Loc)
- return llvm::None;
+ return None;
auto Uri = URI::parse(Loc.FileURI);
if (!Uri) {
log("Could not parse URI: {0}", Loc.FileURI);
- return llvm::None;
+ return None;
}
auto Path = URI::resolve(*Uri, HintPath);
if (!Path) {
log("Could not resolve URI: {0}", Loc.FileURI);
- return llvm::None;
+ return None;
}
Location LSPLoc;
LSPLoc.uri = URIForFile(*Path);
@@ -88,7 +88,7 @@ class DeclarationAndMacrosFinder : publi
// explicitly in the code.
// True means the declaration is explicitly referenced at least once; false
// otherwise.
- llvm::DenseMap<const Decl *, bool> Decls;
+ DenseMap<const Decl *, bool> Decls;
const SourceLocation &SearchedLocation;
const ASTContext &AST;
Preprocessor &PP;
@@ -146,10 +146,10 @@ public:
// expression returned by handleDeclOccurence contains exactly one
// child expression.
const auto *FirstChild = *E->child_begin();
- return llvm::isa<ExprWithCleanups>(FirstChild) ||
- llvm::isa<MaterializeTemporaryExpr>(FirstChild) ||
- llvm::isa<CXXBindTemporaryExpr>(FirstChild) ||
- llvm::isa<ImplicitCastExpr>(FirstChild);
+ return isa<ExprWithCleanups>(FirstChild) ||
+ isa<MaterializeTemporaryExpr>(FirstChild) ||
+ isa<CXXBindTemporaryExpr>(FirstChild) ||
+ isa<ImplicitCastExpr>(FirstChild);
};
bool IsExplicit = !hasImplicitExpr(ASTNode.OrigE);
@@ -224,15 +224,15 @@ Range getTokenRange(ParsedAST &AST, Sour
sourceLocToPosition(SourceMgr, LocEnd)};
}
-llvm::Optional<Location> makeLocation(ParsedAST &AST, SourceLocation TokLoc) {
+Optional<Location> makeLocation(ParsedAST &AST, SourceLocation TokLoc) {
const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
const FileEntry *F = SourceMgr.getFileEntryForID(SourceMgr.getFileID(TokLoc));
if (!F)
- return llvm::None;
+ return None;
auto FilePath = getRealPath(F, SourceMgr);
if (!FilePath) {
log("failed to get path!");
- return llvm::None;
+ return None;
}
Location L;
L.uri = URIForFile(*FilePath);
@@ -288,12 +288,12 @@ std::vector<Location> findDefinitions(Pa
// 4. Return all populated locations for all symbols, definition first (
// which we think is the users wants most often).
struct CandidateLocation {
- llvm::Optional<Location> Def;
- llvm::Optional<Location> Decl;
+ Optional<Location> Def;
+ Optional<Location> Decl;
};
// We respect the order in Symbols.Decls.
- llvm::SmallVector<CandidateLocation, 8> ResultCandidates;
- llvm::DenseMap<SymbolID, size_t> CandidatesIndex;
+ SmallVector<CandidateLocation, 8> ResultCandidates;
+ DenseMap<SymbolID, size_t> CandidatesIndex;
// Emit all symbol locations (declaration or definition) from AST.
for (const DeclInfo &DI : Symbols.Decls) {
@@ -407,7 +407,7 @@ public:
}
private:
- llvm::SmallSet<const Decl *, 4> CanonicalTargets;
+ SmallSet<const Decl *, 4> CanonicalTargets;
std::vector<Reference> References;
const ASTContext &AST;
};
@@ -473,7 +473,7 @@ static std::string typeDeclToString(cons
printingPolicyForDecls(TD->getASTContext().getPrintingPolicy());
std::string Name;
- llvm::raw_string_ostream Stream(Name);
+ raw_string_ostream Stream(Name);
Type.print(Stream, Policy);
return Stream.str();
@@ -487,7 +487,7 @@ static std::string namedDeclQualifiedNam
printingPolicyForDecls(ND->getASTContext().getPrintingPolicy());
std::string Name;
- llvm::raw_string_ostream Stream(Name);
+ raw_string_ostream Stream(Name);
Stream << Prefix << ' ';
ND->printQualifiedName(Stream, Policy);
@@ -497,7 +497,7 @@ static std::string namedDeclQualifiedNam
/// 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 llvm::Optional<std::string> getScopeName(const Decl *D) {
+static Optional<std::string> getScopeName(const Decl *D) {
const DeclContext *DC = D->getDeclContext();
if (isa<TranslationUnitDecl>(DC))
@@ -509,13 +509,13 @@ static llvm::Optional<std::string> getSc
else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
return namedDeclQualifiedName(FD, "function");
- return llvm::None;
+ return None;
}
/// Generate a \p Hover object given the declaration \p D.
static Hover getHoverContents(const Decl *D) {
Hover H;
- llvm::Optional<std::string> NamedScope = getScopeName(D);
+ Optional<std::string> NamedScope = getScopeName(D);
// Generate the "Declared in" section.
if (NamedScope) {
@@ -531,7 +531,7 @@ static Hover getHoverContents(const Decl
D = TD;
std::string DeclText;
- llvm::raw_string_ostream OS(DeclText);
+ raw_string_ostream OS(DeclText);
PrintingPolicy Policy =
printingPolicyForDecls(D->getASTContext().getPrintingPolicy());
@@ -548,7 +548,7 @@ static Hover getHoverContents(const Decl
static Hover getHoverContents(QualType T, ASTContext &ASTCtx) {
Hover H;
std::string TypeText;
- llvm::raw_string_ostream OS(TypeText);
+ raw_string_ostream OS(TypeText);
PrintingPolicy Policy = printingPolicyForDecls(ASTCtx.getPrintingPolicy());
T.print(OS, Policy);
OS.flush();
@@ -577,13 +577,13 @@ namespace {
/// a deduced type set. The AST should be improved to simplify this scenario.
class DeducedTypeVisitor : public RecursiveASTVisitor<DeducedTypeVisitor> {
SourceLocation SearchedLocation;
- llvm::Optional<QualType> DeducedType;
+ Optional<QualType> DeducedType;
public:
DeducedTypeVisitor(SourceLocation SearchedLocation)
: SearchedLocation(SearchedLocation) {}
- llvm::Optional<QualType> getDeducedType() { return DeducedType; }
+ Optional<QualType> getDeducedType() { return DeducedType; }
// Remove the surrounding Reference or Pointer type of the given type T.
QualType UnwrapReferenceOrPointer(QualType T) {
@@ -674,8 +674,8 @@ public:
} // namespace
/// Retrieves the deduced type at a given location (auto, decltype).
-llvm::Optional<QualType> getDeducedType(ParsedAST &AST,
- SourceLocation SourceLocationBeg) {
+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.
Modified: clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp (original)
+++ clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp Sat Oct 20 08:30:37 2018
@@ -21,6 +21,7 @@
const char *IndexFilename;
const char *RequestsFilename;
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -40,17 +41,16 @@ std::vector<FuzzyFindRequest> extractQue
std::istreambuf_iterator<char>());
std::vector<FuzzyFindRequest> Requests;
- auto JSONArray = llvm::json::parse(Log);
+ auto JSONArray = json::parse(Log);
// Panic if the provided file couldn't be parsed.
if (!JSONArray) {
- llvm::errs() << "Error when parsing JSON requests file: "
- << llvm::toString(JSONArray.takeError());
+ errs() << "Error when parsing JSON requests file: "
+ << toString(JSONArray.takeError());
exit(1);
}
if (!JSONArray->getAsArray()) {
- llvm::errs() << "Error: top-level value is not a JSON array: " << Log
- << '\n';
+ errs() << "Error: top-level value is not a JSON array: " << Log << '\n';
exit(1);
}
@@ -58,7 +58,7 @@ std::vector<FuzzyFindRequest> extractQue
FuzzyFindRequest Request;
// Panic if the provided file couldn't be parsed.
if (!fromJSON(Item, Request)) {
- llvm::errs() << "Error when deserializing request: " << Item << '\n';
+ 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) {
- llvm::errs() << "Usage: " << argv[0]
- << " global-symbol-index.yaml requests.json "
- "BENCHMARK_OPTIONS...\n";
+ errs() << "Usage: " << argv[0]
+ << " global-symbol-index.yaml requests.json "
+ "BENCHMARK_OPTIONS...\n";
return -1;
}
IndexFilename = argv[1];
Modified: clang-tools-extra/trunk/clangd/index/Background.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Background.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/Background.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Background.cpp Sat Oct 20 08:30:37 2018
@@ -25,7 +25,7 @@ namespace clangd {
BackgroundIndex::BackgroundIndex(Context BackgroundContext,
StringRef ResourceDir,
const FileSystemProvider &FSProvider)
- : SwapIndex(llvm::make_unique<MemIndex>()), ResourceDir(ResourceDir),
+ : SwapIndex(make_unique<MemIndex>()), ResourceDir(ResourceDir),
FSProvider(FSProvider), BackgroundContext(std::move(BackgroundContext)),
Thread([this] { run(); }) {}
@@ -45,7 +45,7 @@ void BackgroundIndex::stop() {
void BackgroundIndex::run() {
WithContext Background(std::move(BackgroundContext));
while (true) {
- llvm::Optional<Task> Task;
+ Optional<Task> Task;
{
std::unique_lock<std::mutex> Lock(QueueMu);
QueueCV.wait(Lock, [&] { return ShouldStop || !Queue.empty(); });
@@ -111,15 +111,15 @@ void BackgroundIndex::enqueueLocked(tool
std::move(Cmd)));
}
-llvm::Error BackgroundIndex::index(tooling::CompileCommand Cmd) {
+Error BackgroundIndex::index(tooling::CompileCommand Cmd) {
trace::Span Tracer("BackgroundIndex");
SPAN_ATTACH(Tracer, "file", Cmd.Filename);
SmallString<128> AbsolutePath;
- if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+ if (sys::path::is_absolute(Cmd.Filename)) {
AbsolutePath = Cmd.Filename;
} else {
AbsolutePath = Cmd.Directory;
- llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+ sys::path::append(AbsolutePath, Cmd.Filename);
}
auto FS = FSProvider.getFileSystem();
@@ -141,14 +141,14 @@ llvm::Error BackgroundIndex::index(tooli
Inputs.CompileCommand = std::move(Cmd);
auto CI = buildCompilerInvocation(Inputs);
if (!CI)
- return createStringError(llvm::inconvertibleErrorCode(),
+ return createStringError(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(llvm::inconvertibleErrorCode(),
+ return createStringError(inconvertibleErrorCode(),
"Couldn't build compiler instance");
SymbolCollector::Options IndexOpts;
@@ -166,11 +166,10 @@ llvm::Error BackgroundIndex::index(tooli
const FrontendInputFile &Input = Clang->getFrontendOpts().Inputs.front();
if (!Action->BeginSourceFile(*Clang, Input))
- return createStringError(llvm::inconvertibleErrorCode(),
+ return createStringError(inconvertibleErrorCode(),
"BeginSourceFile() failed");
if (!Action->Execute())
- return createStringError(llvm::inconvertibleErrorCode(),
- "Execute() failed");
+ return createStringError(inconvertibleErrorCode(), "Execute() failed");
Action->EndSourceFile();
log("Indexed {0} ({1} symbols, {2} refs)", Inputs.CompileCommand.Filename,
Modified: clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp Sat Oct 20 08:30:37 2018
@@ -13,40 +13,39 @@
#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(llvm::StringRef Suffix,
- llvm::StringRef CanonicalPath) {
- int Components = std::distance(llvm::sys::path::begin(Suffix),
- llvm::sys::path::end(Suffix));
+void CanonicalIncludes::addPathSuffixMapping(StringRef Suffix,
+ StringRef CanonicalPath) {
+ int Components =
+ std::distance(sys::path::begin(Suffix), sys::path::end(Suffix));
MaxSuffixComponents = std::max(MaxSuffixComponents, Components);
SuffixHeaderMapping[Suffix] = CanonicalPath;
}
-void CanonicalIncludes::addMapping(llvm::StringRef Path,
- llvm::StringRef CanonicalPath) {
+void CanonicalIncludes::addMapping(StringRef Path, StringRef CanonicalPath) {
FullPathMapping[Path] = CanonicalPath;
}
-void CanonicalIncludes::addSymbolMapping(llvm::StringRef QualifiedName,
- llvm::StringRef CanonicalPath) {
+void CanonicalIncludes::addSymbolMapping(StringRef QualifiedName,
+ StringRef CanonicalPath) {
this->SymbolMapping[QualifiedName] = CanonicalPath;
}
-llvm::StringRef
-CanonicalIncludes::mapHeader(llvm::ArrayRef<std::string> Headers,
- llvm::StringRef QualifiedName) const {
+StringRef CanonicalIncludes::mapHeader(ArrayRef<std::string> Headers,
+ 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, [](llvm::StringRef Include) {
+ auto I = llvm::find_if(Headers, [](StringRef Include) {
// Skip .inc file whose including header file should
// be #included instead.
return !Include.endswith(".inc");
@@ -56,7 +55,7 @@ CanonicalIncludes::mapHeader(llvm::Array
StringRef Header = *I;
// If Header is not expected be included (e.g. .cc file), we fall back to
// the declaring header.
- StringRef Ext = llvm::sys::path::extension(Header).trim('.');
+ StringRef Ext = 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);
@@ -69,8 +68,7 @@ CanonicalIncludes::mapHeader(llvm::Array
return MapIt->second;
int Components = 1;
- for (auto It = llvm::sys::path::rbegin(Header),
- End = llvm::sys::path::rend(Header);
+ for (auto It = sys::path::rbegin(Header), End = sys::path::rend(Header);
It != End && Components <= MaxSuffixComponents; ++It, ++Components) {
auto SubPath = Header.substr(It->data() - Header.begin());
auto MappingIt = SuffixHeaderMapping.find(SubPath);
Modified: clang-tools-extra/trunk/clangd/index/FileIndex.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/FileIndex.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/FileIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/FileIndex.cpp Sat Oct 20 08:30:37 2018
@@ -19,13 +19,14 @@
#include "clang/Lex/Preprocessor.h"
#include <memory>
+using namespace llvm;
namespace clang {
namespace clangd {
static std::pair<SymbolSlab, RefSlab>
indexSymbols(ASTContext &AST, std::shared_ptr<Preprocessor> PP,
- llvm::ArrayRef<Decl *> DeclsToIndex, bool IsIndexMainAST,
- llvm::ArrayRef<std::string> URISchemes) {
+ ArrayRef<Decl *> DeclsToIndex, bool IsIndexMainAST,
+ ArrayRef<std::string> URISchemes) {
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
@@ -70,14 +71,14 @@ indexSymbols(ASTContext &AST, std::share
}
std::pair<SymbolSlab, RefSlab>
-indexMainDecls(ParsedAST &AST, llvm::ArrayRef<std::string> URISchemes) {
+indexMainDecls(ParsedAST &AST, ArrayRef<std::string> URISchemes) {
return indexSymbols(AST.getASTContext(), AST.getPreprocessorPtr(),
AST.getLocalTopLevelDecls(),
/*IsIndexMainAST=*/true, URISchemes);
}
SymbolSlab indexHeaderSymbols(ASTContext &AST, std::shared_ptr<Preprocessor> PP,
- llvm::ArrayRef<std::string> URISchemes) {
+ ArrayRef<std::string> URISchemes) {
std::vector<Decl *> DeclsToIndex(
AST.getTranslationUnitDecl()->decls().begin(),
AST.getTranslationUnitDecl()->decls().end());
@@ -116,9 +117,9 @@ FileSymbols::buildIndex(IndexType Type,
AllSymbols.push_back(&Sym);
std::vector<Ref> RefsStorage; // Contiguous ranges for each SymbolID.
- llvm::DenseMap<SymbolID, ArrayRef<Ref>> AllRefs;
+ DenseMap<SymbolID, ArrayRef<Ref>> AllRefs;
{
- llvm::DenseMap<SymbolID, SmallVector<Ref, 4>> MergedRefs;
+ DenseMap<SymbolID, SmallVector<Ref, 4>> MergedRefs;
size_t Count = 0;
for (const auto &RefSlab : RefSlabs)
for (const auto &Sym : *RefSlab) {
@@ -149,13 +150,13 @@ FileSymbols::buildIndex(IndexType Type,
switch (Type) {
case IndexType::Light:
return llvm::make_unique<MemIndex>(
- llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
+ make_pointee_range(AllSymbols), std::move(AllRefs),
std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
std::move(RefsStorage)),
StorageSize);
case IndexType::Heavy:
return llvm::make_unique<dex::Dex>(
- llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
+ make_pointee_range(AllSymbols), std::move(AllRefs),
std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
std::move(RefsStorage)),
StorageSize, std::move(URISchemes));
Modified: clang-tools-extra/trunk/clangd/index/Index.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/Index.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Index.cpp Sat Oct 20 08:30:37 2018
@@ -15,9 +15,9 @@
#include "llvm/Support/SHA1.h"
#include "llvm/Support/raw_ostream.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
constexpr uint32_t SymbolLocation::Position::MaxLine;
constexpr uint32_t SymbolLocation::Position::MaxColumn;
@@ -50,7 +50,7 @@ raw_ostream &operator<<(raw_ostream &OS,
return OS << toHex(ID.raw());
}
-SymbolID SymbolID::fromRaw(llvm::StringRef Raw) {
+SymbolID SymbolID::fromRaw(StringRef Raw) {
SymbolID ID;
assert(Raw.size() == RawSize);
memcpy(ID.HashValue.data(), Raw.data(), RawSize);
@@ -59,12 +59,12 @@ SymbolID SymbolID::fromRaw(llvm::StringR
std::string SymbolID::str() const { return toHex(raw()); }
-llvm::Expected<SymbolID> SymbolID::fromStr(llvm::StringRef Str) {
+Expected<SymbolID> SymbolID::fromStr(StringRef Str) {
if (Str.size() != RawSize * 2)
- return createStringError(llvm::inconvertibleErrorCode(), "Bad ID length");
+ return createStringError(inconvertibleErrorCode(), "Bad ID length");
for (char C : Str)
if (!isHexDigit(C))
- return createStringError(llvm::inconvertibleErrorCode(), "Bad hex ID");
+ return createStringError(inconvertibleErrorCode(), "Bad hex ID");
return fromRaw(fromHex(Str));
}
@@ -111,7 +111,7 @@ SymbolSlab::const_iterator SymbolSlab::f
}
// Copy the underlying data of the symbol into the owned arena.
-static void own(Symbol &S, llvm::UniqueStringSaver &Strings) {
+static void own(Symbol &S, UniqueStringSaver &Strings) {
visitStrings(S, [&](StringRef &V) { V = Strings.save(V); });
}
@@ -133,7 +133,7 @@ SymbolSlab SymbolSlab::Builder::build()
[](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;
- llvm::UniqueStringSaver Strings(NewArena);
+ UniqueStringSaver Strings(NewArena);
for (auto &S : Symbols)
own(S, Strings);
return SymbolSlab(std::move(NewArena), std::move(Symbols));
@@ -155,7 +155,7 @@ raw_ostream &operator<<(raw_ostream &OS,
return OS;
}
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Ref &R) {
+raw_ostream &operator<<(raw_ostream &OS, const Ref &R) {
return OS << R.Location << ":" << R.Kind;
}
@@ -199,7 +199,7 @@ std::shared_ptr<SymbolIndex> SwapIndex::
return Index;
}
-bool fromJSON(const llvm::json::Value &Parameters, FuzzyFindRequest &Request) {
+bool fromJSON(const json::Value &Parameters, FuzzyFindRequest &Request) {
json::ObjectMapper O(Parameters);
int64_t Limit;
bool OK =
@@ -212,7 +212,7 @@ bool fromJSON(const llvm::json::Value &P
return OK;
}
-llvm::json::Value toJSON(const FuzzyFindRequest &Request) {
+json::Value toJSON(const FuzzyFindRequest &Request) {
return json::Object{
{"Query", Request.Query},
{"Scopes", json::Array{Request.Scopes}},
@@ -223,15 +223,15 @@ llvm::json::Value toJSON(const FuzzyFind
}
bool SwapIndex::fuzzyFind(const FuzzyFindRequest &R,
- llvm::function_ref<void(const Symbol &)> CB) const {
+ function_ref<void(const Symbol &)> CB) const {
return snapshot()->fuzzyFind(R, CB);
}
void SwapIndex::lookup(const LookupRequest &R,
- llvm::function_ref<void(const Symbol &)> CB) const {
+ function_ref<void(const Symbol &)> CB) const {
return snapshot()->lookup(R, CB);
}
void SwapIndex::refs(const RefsRequest &R,
- llvm::function_ref<void(const Ref &)> CB) const {
+ function_ref<void(const Ref &)> CB) const {
return snapshot()->refs(R, CB);
}
size_t SwapIndex::estimateMemoryUsage() const {
Modified: clang-tools-extra/trunk/clangd/index/IndexAction.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/IndexAction.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/IndexAction.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/IndexAction.cpp Sat Oct 20 08:30:37 2018
@@ -3,6 +3,8 @@
#include "clang/Index/IndexDataConsumer.h"
#include "clang/Index/IndexingAction.h"
#include "clang/Tooling/Tooling.h"
+
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -38,7 +40,7 @@ public:
const auto &CI = getCompilerInstance();
if (CI.hasDiagnostics() &&
CI.getDiagnostics().hasUncompilableErrorOccurred()) {
- llvm::errs() << "Skipping TU due to uncompilable errors\n";
+ errs() << "Skipping TU due to uncompilable errors\n";
return;
}
SymbolsCallback(Collector->takeSymbols());
Modified: clang-tools-extra/trunk/clangd/index/MemIndex.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/MemIndex.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/MemIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/MemIndex.cpp Sat Oct 20 08:30:37 2018
@@ -13,6 +13,7 @@
#include "Quality.h"
#include "Trace.h"
+using namespace llvm;
namespace clang {
namespace clangd {
@@ -24,9 +25,8 @@ std::unique_ptr<SymbolIndex> MemIndex::b
BackingDataSize);
}
-bool MemIndex::fuzzyFind(
- const FuzzyFindRequest &Req,
- llvm::function_ref<void(const Symbol &)> Callback) const {
+bool MemIndex::fuzzyFind(const FuzzyFindRequest &Req,
+ function_ref<void(const Symbol &)> Callback) const {
assert(!StringRef(Req.Query).contains("::") &&
"There must be no :: in query.");
trace::Span Tracer("MemIndex fuzzyFind");
@@ -40,7 +40,7 @@ bool MemIndex::fuzzyFind(
// Exact match against all possible scopes.
if (!Req.AnyScope && !Req.Scopes.empty() &&
- !llvm::is_contained(Req.Scopes, Sym->Scope))
+ !is_contained(Req.Scopes, Sym->Scope))
continue;
if (Req.RestrictForCodeCompletion &&
!(Sym->Flags & Symbol::IndexedForCodeCompletion))
@@ -58,7 +58,7 @@ bool MemIndex::fuzzyFind(
}
void MemIndex::lookup(const LookupRequest &Req,
- llvm::function_ref<void(const Symbol &)> Callback) const {
+ function_ref<void(const Symbol &)> Callback) const {
trace::Span Tracer("MemIndex lookup");
for (const auto &ID : Req.IDs) {
auto I = Index.find(ID);
@@ -68,7 +68,7 @@ void MemIndex::lookup(const LookupReques
}
void MemIndex::refs(const RefsRequest &Req,
- llvm::function_ref<void(const Ref &)> Callback) const {
+ function_ref<void(const Ref &)> Callback) const {
trace::Span Tracer("MemIndex refs");
for (const auto &ReqID : Req.IDs) {
auto SymRefs = Refs.find(ReqID);
Modified: clang-tools-extra/trunk/clangd/index/Merge.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Merge.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/Merge.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Merge.cpp Sat Oct 20 08:30:37 2018
@@ -14,11 +14,10 @@
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/raw_ostream.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
-
// FIXME: Deleted symbols in dirty files are still returned (from Static).
// To identify these eliminate these, we should:
// - find the generating file from each Symbol which is Static-only
@@ -63,9 +62,8 @@ bool MergedIndex::fuzzyFind(const FuzzyF
return More;
}
-void MergedIndex::lookup(
- const LookupRequest &Req,
- llvm::function_ref<void(const Symbol &)> Callback) const {
+void MergedIndex::lookup(const LookupRequest &Req,
+ function_ref<void(const Symbol &)> Callback) const {
trace::Span Tracer("MergedIndex lookup");
SymbolSlab::Builder B;
@@ -86,7 +84,7 @@ void MergedIndex::lookup(
}
void MergedIndex::refs(const RefsRequest &Req,
- llvm::function_ref<void(const Ref &)> Callback) const {
+ 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.
@@ -96,7 +94,7 @@ void MergedIndex::refs(const RefsRequest
// 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.
- llvm::StringSet<> DynamicIndexFileURIs;
+ StringSet<> DynamicIndexFileURIs;
Dynamic->refs(Req, [&](const Ref &O) {
DynamicIndexFileURIs.insert(O.Location.FileURI);
Callback(O);
Modified: clang-tools-extra/trunk/clangd/index/Serialization.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Serialization.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp Sat Oct 20 08:30:37 2018
@@ -448,7 +448,7 @@ void writeRIFF(const IndexFileOut &Data,
void writeYAML(const IndexFileOut &, raw_ostream &);
Expected<IndexFileIn> readYAML(StringRef);
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const IndexFileOut &O) {
+raw_ostream &operator<<(raw_ostream &OS, const IndexFileOut &O) {
switch (O.Format) {
case IndexFileFormat::RIFF:
writeRIFF(O, OS);
@@ -467,17 +467,17 @@ Expected<IndexFileIn> readIndexFile(Stri
return std::move(*YAMLContents);
} else {
return makeError("Not a RIFF file and failed to parse as YAML: " +
- llvm::toString(YAMLContents.takeError()));
+ toString(YAMLContents.takeError()));
}
}
-std::unique_ptr<SymbolIndex> loadIndex(llvm::StringRef SymbolFilename,
- llvm::ArrayRef<std::string> URISchemes,
+std::unique_ptr<SymbolIndex> loadIndex(StringRef SymbolFilename,
+ ArrayRef<std::string> URISchemes,
bool UseDex) {
trace::Span OverallTracer("LoadIndex");
auto Buffer = MemoryBuffer::getFile(SymbolFilename);
if (!Buffer) {
- llvm::errs() << "Can't open " << SymbolFilename << "\n";
+ errs() << "Can't open " << SymbolFilename << "\n";
return nullptr;
}
@@ -491,7 +491,7 @@ std::unique_ptr<SymbolIndex> loadIndex(l
if (I->Refs)
Refs = std::move(*I->Refs);
} else {
- llvm::errs() << "Bad Index: " << llvm::toString(I.takeError()) << "\n";
+ errs() << "Bad Index: " << toString(I.takeError()) << "\n";
return nullptr;
}
}
Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Sat Oct 20 08:30:37 2018
@@ -29,10 +29,11 @@
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-
namespace {
+
/// If \p ND is a template specialization, returns the described template.
/// Otherwise, returns \p ND.
const NamedDecl &getTemplateOrThis(const NamedDecl &ND) {
@@ -50,14 +51,14 @@ const NamedDecl &getTemplateOrThis(const
//
// The Path can be a path relative to the build directory, or retrieved from
// the SourceManager.
-llvm::Optional<std::string> toURI(const SourceManager &SM, StringRef Path,
- const SymbolCollector::Options &Opts) {
- llvm::SmallString<128> AbsolutePath(Path);
+Optional<std::string> toURI(const SourceManager &SM, StringRef Path,
+ const SymbolCollector::Options &Opts) {
+ SmallString<128> AbsolutePath(Path);
if (std::error_code EC =
SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
AbsolutePath))
log("Warning: could not make absolute file: {0}", EC.message());
- if (llvm::sys::path::is_absolute(AbsolutePath)) {
+ if (sys::path::is_absolute(AbsolutePath)) {
// Handle the symbolic link path case where the current working directory
// (getCurrentWorkingDirectory) is a symlink./ We always want to the real
// file path (instead of the symlink path) for the C++ symbols.
@@ -70,28 +71,28 @@ llvm::Optional<std::string> toURI(const
// The file path of Symbol is "/project/src/foo.h" instead of
// "/tmp/build/foo.h"
if (const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
- llvm::sys::path::parent_path(AbsolutePath.str()))) {
+ sys::path::parent_path(AbsolutePath.str()))) {
StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
SmallString<128> AbsoluteFilename;
- llvm::sys::path::append(AbsoluteFilename, DirName,
- llvm::sys::path::filename(AbsolutePath.str()));
+ sys::path::append(AbsoluteFilename, DirName,
+ sys::path::filename(AbsolutePath.str()));
AbsolutePath = AbsoluteFilename;
}
} else if (!Opts.FallbackDir.empty()) {
- llvm::sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath);
+ sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath);
}
- llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
+ sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
std::string ErrMsg;
for (const auto &Scheme : Opts.URISchemes) {
auto U = URI::create(AbsolutePath, Scheme);
if (U)
return U->toString();
- ErrMsg += llvm::toString(U.takeError()) + "\n";
+ ErrMsg += toString(U.takeError()) + "\n";
}
log("Failed to create an URI for file {0}: {1}", AbsolutePath, ErrMsg);
- return llvm::None;
+ return None;
}
// All proto generated headers should start with this line.
@@ -130,7 +131,7 @@ bool isPrivateProtoDecl(const NamedDecl
// 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) || llvm::any_of(Name, islower);
+ return (ND.getKind() != Decl::EnumConstant) || any_of(Name, islower);
}
// We only collect #include paths for symbols that are suitable for global code
@@ -158,9 +159,9 @@ bool shouldCollectIncludePath(index::Sym
/// 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.
-llvm::Optional<std::string>
-getIncludeHeader(llvm::StringRef QName, const SourceManager &SM,
- SourceLocation Loc, const SymbolCollector::Options &Opts) {
+Optional<std::string> getIncludeHeader(StringRef QName, const SourceManager &SM,
+ SourceLocation Loc,
+ const SymbolCollector::Options &Opts) {
std::vector<std::string> Headers;
// Collect the #include stack.
while (true) {
@@ -175,8 +176,8 @@ getIncludeHeader(llvm::StringRef QName,
Loc = SM.getIncludeLoc(SM.getFileID(Loc));
}
if (Headers.empty())
- return llvm::None;
- llvm::StringRef Header = Headers[0];
+ return None;
+ StringRef Header = Headers[0];
if (Opts.Includes) {
Header = Opts.Includes->mapHeader(Headers, QName);
if (Header.startswith("<") || Header.startswith("\""))
@@ -203,14 +204,14 @@ getTokenRange(SourceLocation TokLoc, con
}
// Return the symbol location of the token at \p TokLoc.
-llvm::Optional<SymbolLocation>
-getTokenLocation(SourceLocation TokLoc, const SourceManager &SM,
- const SymbolCollector::Options &Opts,
- const clang::LangOptions &LangOpts,
- std::string &FileURIStorage) {
+Optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc,
+ const SourceManager &SM,
+ const SymbolCollector::Options &Opts,
+ const clang::LangOptions &LangOpts,
+ std::string &FileURIStorage) {
auto U = toURI(SM, SM.getFilename(TokLoc), Opts);
if (!U)
- return llvm::None;
+ return None;
FileURIStorage = std::move(*U);
SymbolLocation Result;
Result.FileURI = FileURIStorage;
@@ -230,7 +231,7 @@ getTokenLocation(SourceLocation TokLoc,
bool isPreferredDeclaration(const NamedDecl &ND, index::SymbolRoleSet Roles) {
const auto& SM = ND.getASTContext().getSourceManager();
return (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) &&
- llvm::isa<TagDecl>(&ND) &&
+ isa<TagDecl>(&ND) &&
!SM.isWrittenInMainFile(SM.getExpansionLoc(ND.getLocation()));
}
@@ -239,7 +240,7 @@ RefKind toRefKind(index::SymbolRoleSet R
}
template <class T> bool explicitTemplateSpecialization(const NamedDecl &ND) {
- if (const auto *TD = llvm::dyn_cast<T>(&ND))
+ if (const auto *TD = dyn_cast<T>(&ND))
if (TD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
return true;
return false;
@@ -295,7 +296,7 @@ bool SymbolCollector::shouldCollectSymbo
default:
// Record has a few derivations (e.g. CXXRecord, Class specialization), it's
// easier to cast.
- if (!llvm::isa<RecordDecl>(DeclCtx))
+ if (!isa<RecordDecl>(DeclCtx))
return false;
}
if (explicitTemplateSpecialization<FunctionDecl>(ND) ||
@@ -333,7 +334,7 @@ bool SymbolCollector::handleDeclOccurenc
// picked a replacement for D
if (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None)
D = CanonicalDecls.try_emplace(D, ASTNode.OrigD).first->second;
- const NamedDecl *ND = llvm::dyn_cast<NamedDecl>(D);
+ const NamedDecl *ND = dyn_cast<NamedDecl>(D);
if (!ND)
return true;
@@ -476,8 +477,8 @@ void SymbolCollector::finish() {
}
const auto &SM = ASTCtx->getSourceManager();
- llvm::DenseMap<FileID, std::string> URICache;
- auto GetURI = [&](FileID FID) -> llvm::Optional<std::string> {
+ DenseMap<FileID, std::string> URICache;
+ auto GetURI = [&](FileID FID) -> Optional<std::string> {
auto Found = URICache.find(FID);
if (Found == URICache.end()) {
if (auto *FileEntry = SM.getFileEntryForID(FID)) {
@@ -491,7 +492,7 @@ void SymbolCollector::finish() {
// Ignore cases where we can not find a corresponding file entry
// for the loc, thoses are not interesting, e.g. symbols formed
// via macro concatenation.
- return llvm::None;
+ return None;
}
}
return Found->second;
Modified: clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp Sat Oct 20 08:30:37 2018
@@ -26,6 +26,8 @@
#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)
@@ -34,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 {
- llvm::Optional<clang::clangd::Symbol> Symbol;
- llvm::Optional<RefBundle> Refs;
+ Optional<clang::clangd::Symbol> Symbol;
+ Optional<RefBundle> Refs;
};
// A class helps YAML to serialize the 32-bit encoded position (Line&Column),
// as YAMLIO can't directly map bitfields.
@@ -62,14 +64,14 @@ using clang::index::SymbolLanguage;
struct NormalizedSymbolID {
NormalizedSymbolID(IO &) {}
NormalizedSymbolID(IO &, const SymbolID &ID) {
- llvm::raw_string_ostream OS(HexString);
+ raw_string_ostream OS(HexString);
OS << ID;
}
SymbolID denormalize(IO &I) {
auto ID = SymbolID::fromStr(HexString);
if (!ID) {
- I.setError(llvm::toString(ID.takeError()));
+ I.setError(toString(ID.takeError()));
return SymbolID();
}
return *ID;
@@ -273,7 +275,7 @@ namespace clang {
namespace clangd {
void writeYAML(const IndexFileOut &O, raw_ostream &OS) {
- llvm::yaml::Output Yout(OS);
+ yaml::Output Yout(OS);
for (const auto &Sym : *O.Symbols) {
VariantEntry Entry;
Entry.Symbol = Sym;
@@ -290,12 +292,12 @@ void writeYAML(const IndexFileOut &O, ra
Expected<IndexFileIn> readYAML(StringRef Data) {
SymbolSlab::Builder Symbols;
RefSlab::Builder Refs;
- llvm::yaml::Input Yin(Data);
+ yaml::Input Yin(Data);
do {
VariantEntry Variant;
Yin >> Variant;
if (Yin.error())
- return llvm::errorCodeToError(Yin.error());
+ return errorCodeToError(Yin.error());
if (Variant.Symbol)
Symbols.insert(*Variant.Symbol);
if (Variant.Refs)
@@ -312,8 +314,8 @@ Expected<IndexFileIn> readYAML(StringRef
std::string toYAML(const Symbol &S) {
std::string Buf;
{
- llvm::raw_string_ostream OS(Buf);
- llvm::yaml::Output Yout(OS);
+ raw_string_ostream OS(Buf);
+ yaml::Output Yout(OS);
Symbol Sym = S; // copy: Yout<< requires mutability.
Yout << Sym;
}
@@ -324,8 +326,8 @@ std::string toYAML(const std::pair<Symbo
RefBundle Refs = {Data.first, Data.second};
std::string Buf;
{
- llvm::raw_string_ostream OS(Buf);
- llvm::yaml::Output Yout(OS);
+ raw_string_ostream OS(Buf);
+ yaml::Output Yout(OS);
Yout << Refs;
}
return Buf;
Modified: clang-tools-extra/trunk/clangd/index/dex/Dex.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/Dex.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/dex/Dex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Dex.cpp Sat Oct 20 08:30:37 2018
@@ -20,17 +20,17 @@
#include <algorithm>
#include <queue>
+using namespace llvm;
namespace clang {
namespace clangd {
namespace dex {
-std::unique_ptr<SymbolIndex>
-Dex::build(SymbolSlab Symbols, RefSlab Refs,
- llvm::ArrayRef<std::string> URISchemes) {
+std::unique_ptr<SymbolIndex> Dex::build(SymbolSlab Symbols, RefSlab Refs,
+ ArrayRef<std::string> URISchemes) {
auto Size = Symbols.bytes() + Refs.bytes();
auto Data = std::make_pair(std::move(Symbols), std::move(Refs));
- return llvm::make_unique<Dex>(Data.first, Data.second, std::move(Data), Size,
- std::move(URISchemes));
+ return make_unique<Dex>(Data.first, Data.second, std::move(Data), Size,
+ std::move(URISchemes));
}
namespace {
@@ -63,14 +63,12 @@ std::vector<Token> generateSearchTokens(
// Constructs BOOST iterators for Path Proximities.
std::unique_ptr<Iterator> createFileProximityIterator(
- llvm::ArrayRef<std::string> ProximityPaths,
- llvm::ArrayRef<std::string> URISchemes,
- const llvm::DenseMap<Token, PostingList> &InvertedIndex,
- const Corpus &Corpus) {
+ ArrayRef<std::string> ProximityPaths, ArrayRef<std::string> URISchemes,
+ const DenseMap<Token, PostingList> &InvertedIndex, const Corpus &Corpus) {
std::vector<std::unique_ptr<Iterator>> BoostingIterators;
// Deduplicate parent URIs extracted from the ProximityPaths.
- llvm::StringSet<> ParentURIs;
- llvm::StringMap<SourceParams> Sources;
+ StringSet<> ParentURIs;
+ StringMap<SourceParams> Sources;
for (const auto &Path : ProximityPaths) {
Sources[Path] = SourceParams();
auto PathURI = URI::create(Path, URISchemes);
@@ -78,7 +76,7 @@ std::unique_ptr<Iterator> createFileProx
elog("Given ProximityPath {0} is can not be converted to any known URI "
"scheme. fuzzyFind request will ignore it.",
Path);
- llvm::consumeError(PathURI.takeError());
+ consumeError(PathURI.takeError());
continue;
}
const auto PathProximityURIs = generateProximityURIs(PathURI->toString());
@@ -134,7 +132,7 @@ void Dex::buildIndex() {
}
// Populate TempInvertedIndex with lists for index symbols.
- llvm::DenseMap<Token, std::vector<DocID>> TempInvertedIndex;
+ 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))
@@ -157,7 +155,7 @@ std::unique_ptr<Iterator> Dex::iterator(
/// while applying Callback to each symbol in the order of decreasing quality
/// of the matched symbols.
bool Dex::fuzzyFind(const FuzzyFindRequest &Req,
- llvm::function_ref<void(const Symbol &)> Callback) const {
+ function_ref<void(const Symbol &)> Callback) const {
assert(!StringRef(Req.Query).contains("::") &&
"There must be no :: in query.");
trace::Span Tracer("Dex fuzzyFind");
@@ -200,7 +198,7 @@ bool Dex::fuzzyFind(const FuzzyFindReque
// FIXME(kbobyrev): Tune this ratio.
if (Req.Limit)
Root = Corpus.limit(move(Root), *Req.Limit * 100);
- SPAN_ATTACH(Tracer, "query", llvm::to_string(*Root));
+ SPAN_ATTACH(Tracer, "query", to_string(*Root));
vlog("Dex query tree: {0}", *Root);
using IDAndScore = std::pair<DocID, float>;
@@ -214,7 +212,7 @@ bool Dex::fuzzyFind(const FuzzyFindReque
for (const auto &IDAndScore : IDAndScores) {
const DocID SymbolDocID = IDAndScore.first;
const auto *Sym = Symbols[SymbolDocID];
- const llvm::Optional<float> Score = Filter.match(Sym->Name);
+ const Optional<float> Score = Filter.match(Sym->Name);
if (!Score)
continue;
// Combine Fuzzy Matching score, precomputed symbol quality and boosting
@@ -235,7 +233,7 @@ bool Dex::fuzzyFind(const FuzzyFindReque
}
void Dex::lookup(const LookupRequest &Req,
- llvm::function_ref<void(const Symbol &)> Callback) const {
+ function_ref<void(const Symbol &)> Callback) const {
trace::Span Tracer("Dex lookup");
for (const auto &ID : Req.IDs) {
auto I = LookupTable.find(ID);
@@ -245,7 +243,7 @@ void Dex::lookup(const LookupRequest &Re
}
void Dex::refs(const RefsRequest &Req,
- llvm::function_ref<void(const Ref &)> Callback) const {
+ 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))
@@ -264,7 +262,7 @@ size_t Dex::estimateMemoryUsage() const
return Bytes + BackingDataSize;
}
-std::vector<std::string> generateProximityURIs(llvm::StringRef URIPath) {
+std::vector<std::string> generateProximityURIs(StringRef URIPath) {
std::vector<std::string> Result;
auto ParsedURI = URI::parse(URIPath);
assert(ParsedURI &&
@@ -283,7 +281,7 @@ std::vector<std::string> generateProximi
while (!Body.empty() && --Limit > 0) {
// FIXME(kbobyrev): Parsing and encoding path to URIs is not necessary and
// could be optimized.
- Body = llvm::sys::path::parent_path(Body, llvm::sys::path::Style::posix);
+ Body = sys::path::parent_path(Body, sys::path::Style::posix);
URI TokenURI(ParsedURI->scheme(), ParsedURI->authority(), Body);
if (!Body.empty())
Result.emplace_back(TokenURI.toString());
Modified: clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp Sat Oct 20 08:30:37 2018
@@ -13,10 +13,10 @@
#include <cassert>
#include <numeric>
+using namespace llvm;
namespace clang {
namespace clangd {
namespace dex {
-
namespace {
/// Implements Iterator over the intersection of other iterators.
@@ -77,7 +77,7 @@ public:
}
private:
- llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+ raw_ostream &dump(raw_ostream &OS) const override {
OS << "(& ";
auto Separator = "";
for (const auto &Child : Children) {
@@ -198,7 +198,7 @@ public:
}
private:
- llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+ raw_ostream &dump(raw_ostream &OS) const override {
OS << "(| ";
auto Separator = "";
for (const auto &Child : Children) {
@@ -246,9 +246,7 @@ public:
size_t estimateSize() const override { return Size; }
private:
- llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
- return OS << "true";
- }
+ raw_ostream &dump(raw_ostream &OS) const override { return OS << "true"; }
DocID Index = 0;
/// Size of the underlying virtual PostingList.
@@ -273,9 +271,7 @@ public:
size_t estimateSize() const override { return 0; }
private:
- llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
- return OS << "false";
- }
+ raw_ostream &dump(raw_ostream &OS) const override { return OS << "false"; }
};
/// Boost iterator is a wrapper around its child which multiplies scores of
@@ -298,7 +294,7 @@ public:
size_t estimateSize() const override { return Child->estimateSize(); }
private:
- llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+ raw_ostream &dump(raw_ostream &OS) const override {
return OS << "(* " << Factor << ' ' << *Child << ')';
}
@@ -338,7 +334,7 @@ public:
}
private:
- llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+ raw_ostream &dump(raw_ostream &OS) const override {
return OS << "(LIMIT " << Limit << " " << *Child << ')';
}
Modified: clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp Sat Oct 20 08:30:37 2018
@@ -13,10 +13,10 @@
#include "llvm/Support/Error.h"
#include "llvm/Support/MathExtras.h"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace dex {
-
namespace {
/// Implements iterator of PostingList chunks. This requires iterating over two
@@ -24,7 +24,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, llvm::ArrayRef<Chunk> Chunks)
+ explicit ChunkIterator(const Token *Tok, ArrayRef<Chunk> Chunks)
: Tok(Tok), Chunks(Chunks), CurrentChunk(Chunks.begin()) {
if (!Chunks.empty()) {
DecompressedChunk = CurrentChunk->decompress();
@@ -71,7 +71,7 @@ public:
}
private:
- llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+ raw_ostream &dump(raw_ostream &OS) const override {
if (Tok != nullptr)
return OS << *Tok;
OS << '[';
@@ -113,13 +113,13 @@ private:
}
const Token *Tok;
- llvm::ArrayRef<Chunk> Chunks;
+ 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;
- llvm::SmallVector<DocID, Chunk::PayloadSize + 1> DecompressedChunk;
+ SmallVector<DocID, Chunk::PayloadSize + 1> DecompressedChunk;
/// Iterator over DecompressedChunk.
decltype(DecompressedChunk)::iterator CurrentID;
@@ -130,11 +130,11 @@ static constexpr size_t BitsPerEncodingB
/// 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, llvm::MutableArrayRef<uint8_t> &Payload) {
+bool encodeVByte(DocID Delta, 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 + llvm::findLastSet(Delta) / BitsPerEncodingByte;
+ unsigned Width = 1 + findLastSet(Delta) / BitsPerEncodingByte;
if (Width > Payload.size())
return false;
@@ -166,12 +166,12 @@ bool encodeVByte(DocID Delta, llvm::Muta
/// DocIDs 42 47 7000
/// gaps 5 6958
/// Encoding (raw number) 00000101 10110110 00101110
-std::vector<Chunk> encodeStream(llvm::ArrayRef<DocID> Documents) {
+std::vector<Chunk> encodeStream(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();
- llvm::MutableArrayRef<uint8_t> RemainingPayload = Result.back().Payload;
+ 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,9 +185,9 @@ std::vector<Chunk> encodeStream(llvm::Ar
/// Reads variable length DocID from the buffer and updates the buffer size. If
/// the stream is terminated, return None.
-llvm::Optional<DocID> readVByte(llvm::ArrayRef<uint8_t> &Bytes) {
+Optional<DocID> readVByte(ArrayRef<uint8_t> &Bytes) {
if (Bytes.front() == 0 || Bytes.empty())
- return llvm::None;
+ return None;
DocID Result = 0;
bool HasNextByte = true;
for (size_t Length = 0; HasNextByte && !Bytes.empty(); ++Length) {
@@ -203,9 +203,9 @@ llvm::Optional<DocID> readVByte(llvm::Ar
} // namespace
-llvm::SmallVector<DocID, Chunk::PayloadSize + 1> Chunk::decompress() const {
- llvm::SmallVector<DocID, Chunk::PayloadSize + 1> Result{Head};
- llvm::ArrayRef<uint8_t> Bytes(Payload);
+SmallVector<DocID, Chunk::PayloadSize + 1> Chunk::decompress() const {
+ SmallVector<DocID, Chunk::PayloadSize + 1> Result{Head};
+ ArrayRef<uint8_t> Bytes(Payload);
DocID Delta;
for (DocID Current = Head; !Bytes.empty(); Current += Delta) {
auto MaybeDelta = readVByte(Bytes);
@@ -214,10 +214,10 @@ llvm::SmallVector<DocID, Chunk::PayloadS
Delta = *MaybeDelta;
Result.push_back(Current + Delta);
}
- return llvm::SmallVector<DocID, Chunk::PayloadSize + 1>{Result};
+ return SmallVector<DocID, Chunk::PayloadSize + 1>{Result};
}
-PostingList::PostingList(llvm::ArrayRef<DocID> Documents)
+PostingList::PostingList(ArrayRef<DocID> Documents)
: Chunks(encodeStream(Documents)) {}
std::unique_ptr<Iterator> PostingList::iterator(const Token *Tok) const {
Modified: clang-tools-extra/trunk/clangd/index/dex/Trigram.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/Trigram.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/dex/Trigram.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Trigram.cpp Sat Oct 20 08:30:37 2018
@@ -18,16 +18,15 @@
#include <string>
using namespace llvm;
-
namespace clang {
namespace clangd {
namespace dex {
-std::vector<Token> generateIdentifierTrigrams(llvm::StringRef Identifier) {
+std::vector<Token> generateIdentifierTrigrams(StringRef Identifier) {
// Apply fuzzy matching text segmentation.
std::vector<CharRole> Roles(Identifier.size());
calculateRoles(Identifier,
- llvm::makeMutableArrayRef(Roles.data(), Identifier.size()));
+ makeMutableArrayRef(Roles.data(), Identifier.size()));
std::string LowercaseIdentifier = Identifier.lower();
@@ -86,7 +85,7 @@ std::vector<Token> generateIdentifierTri
return {UniqueTrigrams.begin(), UniqueTrigrams.end()};
}
-std::vector<Token> generateQueryTrigrams(llvm::StringRef Query) {
+std::vector<Token> generateQueryTrigrams(StringRef Query) {
if (Query.empty())
return {};
std::string LowercaseQuery = Query.lower();
@@ -95,7 +94,7 @@ std::vector<Token> generateQueryTrigrams
// Apply fuzzy matching text segmentation.
std::vector<CharRole> Roles(Query.size());
- calculateRoles(Query, llvm::makeMutableArrayRef(Roles.data(), Query.size()));
+ calculateRoles(Query, makeMutableArrayRef(Roles.data(), Query.size()));
DenseSet<Token> UniqueTrigrams;
std::string Chars;
Modified: clang-tools-extra/trunk/clangd/index/dex/dexp/Dexp.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/dexp/Dexp.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/dex/dexp/Dexp.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/dexp/Dexp.cpp Sat Oct 20 08:30:37 2018
@@ -22,18 +22,14 @@
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Signals.h"
-using clang::clangd::FuzzyFindRequest;
-using clang::clangd::loadIndex;
-using clang::clangd::Symbol;
-using clang::clangd::SymbolIndex;
using namespace llvm;
+using namespace clang;
+using namespace clangd;
namespace {
-llvm::cl::opt<std::string>
- IndexPath("index-path",
- llvm::cl::desc("Path to the index"),
- llvm::cl::Positional, llvm::cl::Required);
+cl::opt<std::string> IndexPath("index-path", cl::desc("Path to the index"),
+ cl::Positional, cl::Required);
static const std::string Overview = R"(
This is an **experimental** interactive tool to process user-provided search
@@ -44,27 +40,27 @@ and manually construct non-trivial test
Type use "help" request to get information about the details.
)";
-void reportTime(StringRef Name, llvm::function_ref<void()> F) {
+void reportTime(StringRef Name, 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);
- llvm::outs() << llvm::formatv("{0} took {1:ms+n}.\n", Name, Duration);
+ outs() << formatv("{0} took {1:ms+n}.\n", Name, Duration);
}
-std::vector<clang::clangd::SymbolID>
-getSymbolIDsFromIndex(llvm::StringRef QualifiedName, const SymbolIndex *Index) {
+std::vector<SymbolID> getSymbolIDsFromIndex(StringRef QualifiedName,
+ const SymbolIndex *Index) {
FuzzyFindRequest Request;
// Remove leading "::" qualifier as FuzzyFind doesn't need leading "::"
// qualifier for global scope.
bool IsGlobalScope = QualifiedName.consume_front("::");
- auto Names = clang::clangd::splitQualifiedName(QualifiedName);
+ auto Names = splitQualifiedName(QualifiedName);
if (IsGlobalScope || !Names.first.empty())
Request.Scopes = {Names.first};
Request.Query = Names.second;
- std::vector<clang::clangd::SymbolID> SymIDs;
+ std::vector<SymbolID> SymIDs;
Index->fuzzyFind(Request, [&](const Symbol &Sym) {
std::string SymQualifiedName = (Sym.Scope + Sym.Name).str();
if (QualifiedName == SymQualifiedName)
@@ -90,7 +86,7 @@ public:
virtual void parseAndRun(ArrayRef<const char *> Argv, const char *Overview,
const SymbolIndex &Index) {
std::string ParseErrs;
- llvm::raw_string_ostream OS(ParseErrs);
+ raw_string_ostream OS(ParseErrs);
bool Ok =
cl::ParseCommandLineOptions(Argv.size(), Argv.data(), Overview, &OS);
if (Help.getNumOccurrences() > 0) {
@@ -139,18 +135,16 @@ class FuzzyFind : public Command {
Request.Limit = Limit;
Request.Query = Query;
if (Scopes.getNumOccurrences() > 0) {
- llvm::SmallVector<StringRef, 8> Scopes;
+ SmallVector<StringRef, 8> Scopes;
StringRef(this->Scopes).split(Scopes, ',');
Request.Scopes = {Scopes.begin(), Scopes.end()};
}
// FIXME(kbobyrev): Print symbol final scores to see the distribution.
static const auto OutputFormat = "{0,-4} | {1,-40} | {2,-25}\n";
- llvm::outs() << llvm::formatv(OutputFormat, "Rank", "Symbol ID",
- "Symbol Name");
+ outs() << formatv(OutputFormat, "Rank", "Symbol ID", "Symbol Name");
size_t Rank = 0;
Index->fuzzyFind(Request, [&](const Symbol &Sym) {
- llvm::outs() << llvm::formatv(OutputFormat, Rank++, Sym.ID.str(),
- Sym.Name);
+ outs() << formatv(OutputFormat, Rank++, Sym.ID.str(), Sym.Name);
});
}
};
@@ -167,15 +161,14 @@ class Lookup : public Command {
void run() override {
if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {
- llvm::outs()
- << "Missing required argument: please provide id or -name.\n";
+ outs() << "Missing required argument: please provide id or -name.\n";
return;
}
- std::vector<clang::clangd::SymbolID> IDs;
+ std::vector<SymbolID> IDs;
if (ID.getNumOccurrences()) {
- auto SID = clang::clangd::SymbolID::fromStr(ID);
+ auto SID = SymbolID::fromStr(ID);
if (!SID) {
- llvm::outs() << llvm::toString(SID.takeError()) << "\n";
+ outs() << toString(SID.takeError()) << "\n";
return;
}
IDs.push_back(*SID);
@@ -183,15 +176,15 @@ class Lookup : public Command {
IDs = getSymbolIDsFromIndex(Name, Index);
}
- clang::clangd::LookupRequest Request;
+ LookupRequest Request;
Request.IDs.insert(IDs.begin(), IDs.end());
bool FoundSymbol = false;
Index->lookup(Request, [&](const Symbol &Sym) {
FoundSymbol = true;
- llvm::outs() << toYAML(Sym);
+ outs() << toYAML(Sym);
});
if (!FoundSymbol)
- llvm::outs() << "not found\n";
+ outs() << "not found\n";
}
};
@@ -211,32 +204,31 @@ class Refs : public Command {
void run() override {
if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {
- llvm::outs()
- << "Missing required argument: please provide id or -name.\n";
+ outs() << "Missing required argument: please provide id or -name.\n";
return;
}
- std::vector<clang::clangd::SymbolID> IDs;
+ std::vector<SymbolID> IDs;
if (ID.getNumOccurrences()) {
- auto SID = clang::clangd::SymbolID::fromStr(ID);
+ auto SID = SymbolID::fromStr(ID);
if (!SID) {
- llvm::outs() << llvm::toString(SID.takeError()) << "\n";
+ outs() << toString(SID.takeError()) << "\n";
return;
}
IDs.push_back(*SID);
} else {
IDs = getSymbolIDsFromIndex(Name, Index);
}
- clang::clangd::RefsRequest RefRequest;
+ RefsRequest RefRequest;
RefRequest.IDs.insert(IDs.begin(), IDs.end());
- llvm::Regex RegexFilter(Filter);
- Index->refs(RefRequest, [&RegexFilter](const clang::clangd::Ref &R) {
- auto U = clang::clangd::URI::parse(R.Location.FileURI);
+ Regex RegexFilter(Filter);
+ Index->refs(RefRequest, [&RegexFilter](const Ref &R) {
+ auto U = URI::parse(R.Location.FileURI);
if (!U) {
- llvm::outs() << U.takeError();
+ outs() << U.takeError();
return;
}
if (RegexFilter.match(U->body()))
- llvm::outs() << R << "\n";
+ outs() << R << "\n";
});
}
};
@@ -253,16 +245,16 @@ struct {
llvm::make_unique<Refs>},
};
-std::unique_ptr<SymbolIndex> openIndex(llvm::StringRef Index) {
+std::unique_ptr<SymbolIndex> openIndex(StringRef Index) {
return loadIndex(Index, /*URISchemes=*/{}, /*UseDex=*/true);
}
} // namespace
int main(int argc, const char *argv[]) {
- llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
- llvm::cl::ResetCommandLineParser(); // We reuse it for REPL commands.
- llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
+ cl::ParseCommandLineOptions(argc, argv, Overview);
+ cl::ResetCommandLineParser(); // We reuse it for REPL commands.
+ sys::PrintStackTraceOnErrorSignal(argv[0]);
std::unique_ptr<SymbolIndex> Index;
reportTime("Dex build", [&]() {
@@ -270,13 +262,13 @@ int main(int argc, const char *argv[]) {
});
if (!Index) {
- llvm::outs() << "Failed to open the index.\n";
+ outs() << "Failed to open the index.\n";
return -1;
}
- llvm::LineEditor LE("dexp");
+ LineEditor LE("dexp");
- while (llvm::Optional<std::string> Request = LE.readLine()) {
+ while (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;
@@ -286,7 +278,7 @@ int main(int argc, const char *argv[]) {
if (Args.front() == "help") {
outs() << "dexp - Index explorer\nCommands:\n";
for (const auto &C : CommandInfo)
- outs() << llvm::formatv("{0,16} - {1}\n", C.Name, C.Description);
+ outs() << formatv("{0,16} - {1}\n", C.Name, C.Description);
outs() << "Get detailed command help with e.g. `find -help`.\n";
continue;
}
Modified: clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp (original)
+++ clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp Sat Oct 20 08:30:37 2018
@@ -24,19 +24,18 @@
using namespace llvm;
using namespace clang::tooling;
-using clang::clangd::SymbolSlab;
namespace clang {
namespace clangd {
namespace {
-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));
+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));
class IndexActionFactory : public tooling::FrontendActionFactory {
public:
@@ -86,7 +85,7 @@ private:
} // namespace clang
int main(int argc, const char **argv) {
- llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
+ sys::PrintStackTraceOnErrorSignal(argv[0]);
const char *Overview = R"(
Creates an index of symbol information etc in a whole project.
@@ -106,7 +105,7 @@ int main(int argc, const char **argv) {
argc, argv, cl::GeneralCategory, Overview);
if (!Executor) {
- llvm::errs() << llvm::toString(Executor.takeError()) << "\n";
+ errs() << toString(Executor.takeError()) << "\n";
return 1;
}
@@ -115,12 +114,12 @@ int main(int argc, const char **argv) {
auto Err = Executor->get()->execute(
llvm::make_unique<clang::clangd::IndexActionFactory>(Data));
if (Err) {
- llvm::errs() << llvm::toString(std::move(Err)) << "\n";
+ errs() << toString(std::move(Err)) << "\n";
}
// Emit collected data.
clang::clangd::IndexFileOut Out(Data);
Out.Format = clang::clangd::Format;
- llvm::outs() << Out;
+ outs() << Out;
return 0;
}
Modified: clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp (original)
+++ clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp Sat Oct 20 08:30:37 2018
@@ -25,174 +25,168 @@
#include <string>
#include <thread>
+using namespace llvm;
using namespace clang;
using namespace clang::clangd;
// FIXME: remove this option when Dex is cheap enough.
-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<bool> UseDex("use-dex-index",
+ cl::desc("Use experimental Dex dynamic index."),
+ cl::init(false), cl::Hidden);
-static llvm::cl::opt<Path> CompileCommandsDir(
+static cl::opt<Path> CompileCommandsDir(
"compile-commands-dir",
- 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 llvm::cl::opt<unsigned>
- WorkerThreadsCount("j",
- llvm::cl::desc("Number of async workers used by clangd"),
- llvm::cl::init(getDefaultAsyncThreadsCount()));
+ 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()));
// FIXME: also support "plain" style where signatures are always omitted.
enum CompletionStyleFlag { Detailed, Bundled };
-static llvm::cl::opt<CompletionStyleFlag> CompletionStyle(
- "completion-style",
- llvm::cl::desc("Granularity of code completion suggestions"),
- llvm::cl::values(
+static cl::opt<CompletionStyleFlag> CompletionStyle(
+ "completion-style", cl::desc("Granularity of code completion suggestions"),
+ 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.")),
- llvm::cl::init(Detailed));
+ cl::init(Detailed));
// FIXME: Flags are the wrong mechanism for user preferences.
// We should probably read a dotfile or similar.
-static llvm::cl::opt<bool> IncludeIneligibleResults(
+static cl::opt<bool> IncludeIneligibleResults(
"include-ineligible-results",
- llvm::cl::desc(
- "Include ineligible completion results (e.g. private members)"),
- llvm::cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
- llvm::cl::Hidden);
-
-static llvm::cl::opt<JSONStreamStyle> InputStyle(
- "input-style", llvm::cl::desc("Input JSON stream encoding"),
- llvm::cl::values(
+ 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(
clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
clEnumValN(JSONStreamStyle::Delimited, "delimited",
"messages delimited by --- lines, with # comment support")),
- llvm::cl::init(JSONStreamStyle::Standard));
+ cl::init(JSONStreamStyle::Standard));
-static llvm::cl::opt<bool>
- PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
- llvm::cl::init(false));
-
-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> PrettyPrint("pretty", cl::desc("Pretty-print JSON output"),
+ cl::init(false));
-static llvm::cl::opt<bool> Test(
+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 cl::opt<bool> Test(
"lit-test",
- llvm::cl::desc(
+ cl::desc(
"Abbreviation for -input-style=delimited -pretty -run-synchronously. "
"Intended to simplify lit tests."),
- llvm::cl::init(false), llvm::cl::Hidden);
+ cl::init(false), cl::Hidden);
enum PCHStorageFlag { Disk, Memory };
-static llvm::cl::opt<PCHStorageFlag> PCHStorage(
+static cl::opt<PCHStorageFlag> PCHStorage(
"pch-storage",
- 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);
+ 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 llvm::cl::opt<Path> InputMirrorFile(
+static cl::opt<Path> InputMirrorFile(
"input-mirror-file",
- llvm::cl::desc(
+ cl::desc(
"Mirror all LSP input to the specified file. Useful for debugging."),
- llvm::cl::init(""), llvm::cl::Hidden);
+ cl::init(""), cl::Hidden);
-static llvm::cl::opt<bool> EnableIndex(
+static cl::opt<bool> EnableIndex(
"index",
- llvm::cl::desc(
+ 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."),
- llvm::cl::init(true), llvm::cl::Hidden);
+ cl::init(true), cl::Hidden);
-static llvm::cl::opt<bool> AllScopesCompletion(
+static cl::opt<bool> AllScopesCompletion(
"all-scopes-completion",
- llvm::cl::desc(
+ 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."),
- llvm::cl::init(false), llvm::cl::Hidden);
+ cl::init(false), cl::Hidden);
-static llvm::cl::opt<bool>
- ShowOrigins("debug-origin",
- llvm::cl::desc("Show origins of completion items"),
- llvm::cl::init(clangd::CodeCompleteOptions().ShowOrigins),
- llvm::cl::Hidden);
+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> HeaderInsertionDecorators(
+static cl::opt<bool> HeaderInsertionDecorators(
"header-insertion-decorators",
- 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));
+ 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));
-static llvm::cl::opt<Path> IndexFile(
+static cl::opt<Path> IndexFile(
"index-file",
- llvm::cl::desc(
+ 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."),
- llvm::cl::init(""), llvm::cl::Hidden);
+ cl::init(""), cl::Hidden);
enum CompileArgsFrom { LSPCompileArgs, FilesystemCompileArgs };
-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 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 llvm::cl::opt<bool> EnableFunctionArgSnippets(
+static cl::opt<bool> EnableFunctionArgSnippets(
"function-arg-placeholders",
- llvm::cl::desc("When disabled, completions contain only parentheses for "
- "function calls. When enabled, completions also contain "
- "placeholders for method parameters."),
- llvm::cl::init(clangd::CodeCompleteOptions().EnableFunctionArgSnippets));
+ 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));
int main(int argc, char *argv[]) {
- llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
- llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
+ sys::PrintStackTraceOnErrorSignal(argv[0]);
+ cl::SetVersionPrinter([](raw_ostream &OS) {
OS << clang::getClangToolFullVersion("clangd") << "\n";
});
- llvm::cl::ParseCommandLineOptions(
+ 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 directly. "
+ "\n\nIt should be used via an editor plugin rather than invoked "
+ "directly. "
"For more information, see:"
"\n\thttps://clang.llvm.org/extra/clangd.html"
"\n\thttps://microsoft.github.io/language-server-protocol/");
@@ -203,69 +197,68 @@ int main(int argc, char *argv[]) {
}
if (!RunSynchronously && WorkerThreadsCount == 0) {
- llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
- "specify -run-synchronously?";
+ errs() << "A number of worker threads cannot be 0. Did you mean to "
+ "specify -run-synchronously?";
return 1;
}
if (RunSynchronously) {
if (WorkerThreadsCount.getNumOccurrences())
- llvm::errs() << "Ignoring -j because -run-synchronously is set.\n";
+ errs() << "Ignoring -j because -run-synchronously is set.\n";
WorkerThreadsCount = 0;
}
// Validate command line arguments.
- llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
+ Optional<raw_fd_ostream> InputMirrorStream;
if (!InputMirrorFile.empty()) {
std::error_code EC;
InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
- llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
+ sys::fs::FA_Read | sys::fs::FA_Write);
if (EC) {
InputMirrorStream.reset();
- llvm::errs() << "Error while opening an input mirror file: "
- << EC.message();
+ errs() << "Error while opening an input mirror file: " << EC.message();
}
}
// 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.
- llvm::Optional<llvm::raw_fd_ostream> TraceStream;
+ Optional<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,
- llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
+ sys::fs::FA_Read | sys::fs::FA_Write);
if (EC) {
TraceStream.reset();
- llvm::errs() << "Error while opening trace file " << TraceFile << ": "
- << EC.message();
+ errs() << "Error while opening trace file " << TraceFile << ": "
+ << EC.message();
} else {
Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
}
}
- llvm::Optional<trace::Session> TracingSession;
+ 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.
- llvm::errs().SetBuffered();
- StreamLogger Logger(llvm::errs(), LogLevel);
+ errs().SetBuffered();
+ StreamLogger Logger(errs(), LogLevel);
clangd::LoggingSession LoggingSession(Logger);
// If --compile-commands-dir arg was invoked, check value and override default
// path.
- llvm::Optional<Path> CompileCommandsDirPath;
+ Optional<Path> CompileCommandsDirPath;
if (CompileCommandsDir.empty()) {
- CompileCommandsDirPath = llvm::None;
- } else if (!llvm::sys::path::is_absolute(CompileCommandsDir) ||
- !llvm::sys::fs::exists(CompileCommandsDir)) {
- llvm::errs() << "Path specified by --compile-commands-dir either does not "
- "exist or is not an absolute "
- "path. The argument will be ignored.\n";
- CompileCommandsDirPath = llvm::None;
+ CompileCommandsDirPath = None;
+ } else if (!sys::path::is_absolute(CompileCommandsDir) ||
+ !sys::fs::exists(CompileCommandsDir)) {
+ errs() << "Path specified by --compile-commands-dir either does not "
+ "exist or is not an absolute "
+ "path. The argument will be ignored.\n";
+ CompileCommandsDirPath = None;
} else {
CompileCommandsDirPath = CompileCommandsDir;
}
@@ -314,15 +307,15 @@ int main(int argc, char *argv[]) {
// Initialize and run ClangdLSPServer.
// Change stdin to binary to not lose \r\n on windows.
- llvm::sys::ChangeStdinToBinary();
+ sys::ChangeStdinToBinary();
auto Transport = newJSONTransport(
- stdin, llvm::outs(),
+ stdin, outs(),
InputMirrorStream ? InputMirrorStream.getPointer() : nullptr, PrettyPrint,
InputStyle);
ClangdLSPServer LSPServer(
*Transport, CCOpts, CompileCommandsDirPath,
/*ShouldUseInMemoryCDB=*/CompileArgsFrom == LSPCompileArgs, Opts);
constexpr int NoShutdownRequestErrorCode = 1;
- llvm::set_thread_name("clangd.main");
+ set_thread_name("clangd.main");
return LSPServer.run() ? 0 : NoShutdownRequestErrorCode;
}
Modified: clang-tools-extra/trunk/unittests/clangd/Annotations.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/Annotations.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/Annotations.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/Annotations.cpp Sat Oct 20 08:30:37 2018
@@ -10,16 +10,15 @@
#include "Annotations.h"
#include "SourceCode.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
-
// Crash if the assertion fails, printing the message and testcase.
// More elegant error handling isn't needed for unit tests.
-static void require(bool Assertion, const char *Msg, llvm::StringRef Code) {
+static void require(bool Assertion, const char *Msg, StringRef Code) {
if (!Assertion) {
- llvm::errs() << "Annotated testcase: " << Msg << "\n" << Code << "\n";
+ errs() << "Annotated testcase: " << Msg << "\n" << Code << "\n";
llvm_unreachable("Annotated testcase assertion failed!");
}
}
@@ -53,7 +52,7 @@ Annotations::Annotations(StringRef Text)
continue;
}
if (Text.consume_front("$")) {
- Name = Text.take_while(llvm::isAlnum);
+ Name = Text.take_while(isAlnum);
Text = Text.drop_front(Name->size());
continue;
}
@@ -64,23 +63,23 @@ Annotations::Annotations(StringRef Text)
Require(OpenRanges.empty(), "unmatched [[");
}
-Position Annotations::point(llvm::StringRef Name) const {
+Position Annotations::point(StringRef Name) const {
auto I = Points.find(Name);
require(I != Points.end() && I->getValue().size() == 1,
"expected exactly one point", Code);
return I->getValue()[0];
}
-std::vector<Position> Annotations::points(llvm::StringRef Name) const {
+std::vector<Position> Annotations::points(StringRef Name) const {
auto P = Points.lookup(Name);
return {P.begin(), P.end()};
}
-Range Annotations::range(llvm::StringRef Name) const {
+Range Annotations::range(StringRef Name) const {
auto I = Ranges.find(Name);
require(I != Ranges.end() && I->getValue().size() == 1,
"expected exactly one range", Code);
return I->getValue()[0];
}
-std::vector<Range> Annotations::ranges(llvm::StringRef Name) const {
+std::vector<Range> Annotations::ranges(StringRef Name) const {
auto R = Ranges.lookup(Name);
return {R.begin(), R.end()};
}
Modified: clang-tools-extra/trunk/unittests/clangd/CancellationTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/CancellationTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/CancellationTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/CancellationTests.cpp Sat Oct 20 08:30:37 2018
@@ -8,6 +8,7 @@
#include <memory>
#include <thread>
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -21,7 +22,7 @@ TEST(CancellationTest, CancellationTest)
}
TEST(CancellationTest, CancelerDiesContextLives) {
- llvm::Optional<WithContext> ContextWithCancellation;
+ Optional<WithContext> ContextWithCancellation;
{
auto Task = cancelableTask();
ContextWithCancellation.emplace(std::move(Task.first));
Modified: clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp Sat Oct 20 08:30:37 2018
@@ -30,6 +30,7 @@
#include <thread>
#include <vector>
+using namespace llvm;
namespace clang {
namespace clangd {
@@ -104,14 +105,14 @@ public:
private:
mutable std::mutex Mutex;
- llvm::StringMap<bool> LastDiagsHadError;
+ StringMap<bool> LastDiagsHadError;
};
/// Replaces all patterns of the form 0x123abc with spaces
std::string replacePtrsInDump(std::string const &Dump) {
- llvm::Regex RE("0x[0-9a-fA-F]+");
- llvm::SmallVector<StringRef, 1> Matches;
- llvm::StringRef Pending = Dump;
+ Regex RE("0x[0-9a-fA-F]+");
+ SmallVector<StringRef, 1> Matches;
+ StringRef Pending = Dump;
std::string Result;
while (RE.match(Pending, &Matches)) {
@@ -264,7 +265,7 @@ int b = a;
TEST_F(ClangdVFSTest, PropagatesContexts) {
static Key<int> Secret;
struct FSProvider : public FileSystemProvider {
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> getFileSystem() const override {
+ IntrusiveRefCntPtr<vfs::FileSystem> getFileSystem() const override {
Got = Context::current().getExisting(Secret);
return buildTestFS({});
}
@@ -308,19 +309,19 @@ TEST_F(ClangdVFSTest, SearchLibDir) {
// A lib dir for gcc installation
SmallString<64> LibDir("/randomusr/lib/gcc/x86_64-linux-gnu");
- llvm::sys::path::append(LibDir, Version);
+ sys::path::append(LibDir, Version);
// Put crtbegin.o into LibDir/64 to trick clang into thinking there's a gcc
// installation there.
SmallString<64> DummyLibFile;
- llvm::sys::path::append(DummyLibFile, LibDir, "64", "crtbegin.o");
+ sys::path::append(DummyLibFile, LibDir, "64", "crtbegin.o");
FS.Files[DummyLibFile] = "";
SmallString<64> IncludeDir("/randomusr/include/c++");
- llvm::sys::path::append(IncludeDir, Version);
+ sys::path::append(IncludeDir, Version);
SmallString<64> StringPath;
- llvm::sys::path::append(StringPath, IncludeDir, "string");
+ sys::path::append(StringPath, IncludeDir, "string");
FS.Files[StringPath] = "class mock_string {};";
auto FooCpp = testPath("foo.cpp");
@@ -593,7 +594,7 @@ int d;
void onDiagnosticsReady(PathRef File,
std::vector<Diag> Diagnostics) override {
- StringRef FileIndexStr = llvm::sys::path::stem(File);
+ StringRef FileIndexStr = sys::path::stem(File);
ASSERT_TRUE(FileIndexStr.consume_front("Foo"));
unsigned long FileIndex = std::stoul(FileIndexStr.str());
@@ -781,7 +782,7 @@ TEST_F(ClangdVFSTest, CheckSourceHeaderS
FS.Files[FooH] = "int a;";
FS.Files[Invalid] = "int main() { \n return 0; \n }";
- llvm::Optional<Path> PathResult = Server.switchSourceHeader(FooCpp);
+ Optional<Path> PathResult = Server.switchSourceHeader(FooCpp);
EXPECT_TRUE(PathResult.hasValue());
ASSERT_EQ(PathResult.getValue(), FooH);
@@ -970,28 +971,28 @@ TEST_F(ClangdVFSTest, ChangedHeaderFromI
TEST(ClangdTests, PreambleVFSStatCache) {
class ListenStatsFSProvider : public FileSystemProvider {
public:
- ListenStatsFSProvider(llvm::StringMap<unsigned> &CountStats)
+ ListenStatsFSProvider(StringMap<unsigned> &CountStats)
: CountStats(CountStats) {}
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> getFileSystem() const override {
- class ListenStatVFS : public llvm::vfs::ProxyFileSystem {
+ IntrusiveRefCntPtr<vfs::FileSystem> getFileSystem() const override {
+ class ListenStatVFS : public vfs::ProxyFileSystem {
public:
- ListenStatVFS(IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
- llvm::StringMap<unsigned> &CountStats)
+ ListenStatVFS(IntrusiveRefCntPtr<vfs::FileSystem> FS,
+ StringMap<unsigned> &CountStats)
: ProxyFileSystem(std::move(FS)), CountStats(CountStats) {}
- llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
+ ErrorOr<std::unique_ptr<vfs::File>>
openFileForRead(const Twine &Path) override {
- ++CountStats[llvm::sys::path::filename(Path.str())];
+ ++CountStats[sys::path::filename(Path.str())];
return ProxyFileSystem::openFileForRead(Path);
}
- llvm::ErrorOr<llvm::vfs::Status> status(const Twine &Path) override {
- ++CountStats[llvm::sys::path::filename(Path.str())];
+ ErrorOr<vfs::Status> status(const Twine &Path) override {
+ ++CountStats[sys::path::filename(Path.str())];
return ProxyFileSystem::status(Path);
}
private:
- llvm::StringMap<unsigned> &CountStats;
+ StringMap<unsigned> &CountStats;
};
return IntrusiveRefCntPtr<ListenStatVFS>(
@@ -999,11 +1000,11 @@ TEST(ClangdTests, PreambleVFSStatCache)
}
// If relative paths are used, they are resolved with testPath().
- llvm::StringMap<std::string> Files;
- llvm::StringMap<unsigned> &CountStats;
+ StringMap<std::string> Files;
+ StringMap<unsigned> &CountStats;
};
- llvm::StringMap<unsigned> CountStats;
+ StringMap<unsigned> CountStats;
ListenStatsFSProvider FS(CountStats);
ErrorCheckingDiagConsumer DiagConsumer;
MockCompilationDatabase CDB;
Modified: clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp Sat Oct 20 08:30:37 2018
@@ -15,11 +15,11 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
-
namespace {
+
using testing::ElementsAre;
using testing::Field;
using testing::IsEmpty;
@@ -34,24 +34,23 @@ testing::Matcher<const Diag &> WithNote(
}
MATCHER_P2(Diag, Range, Message,
- "Diag at " + llvm::to_string(Range) + " = [" + Message + "]") {
+ "Diag at " + to_string(Range) + " = [" + Message + "]") {
return arg.Range == Range && arg.Message == Message;
}
MATCHER_P3(Fix, Range, Replacement, Message,
- "Fix " + llvm::to_string(Range) + " => " +
+ "Fix " + to_string(Range) + " => " +
testing::PrintToString(Replacement) + " = [" + Message + "]") {
return arg.Message == Message && arg.Edits.size() == 1 &&
arg.Edits[0].range == Range && arg.Edits[0].newText == Replacement;
}
-MATCHER_P(EqualToLSPDiag, LSPDiag,
- "LSP diagnostic " + llvm::to_string(LSPDiag)) {
+MATCHER_P(EqualToLSPDiag, LSPDiag, "LSP diagnostic " + to_string(LSPDiag)) {
return std::tie(arg.range, arg.severity, arg.message) ==
std::tie(LSPDiag.range, LSPDiag.severity, LSPDiag.message);
}
-MATCHER_P(EqualToFix, Fix, "LSP fix " + llvm::to_string(Fix)) {
+MATCHER_P(EqualToFix, Fix, "LSP fix " + to_string(Fix)) {
if (arg.Message != Fix.Message)
return false;
if (arg.Edits.size() != Fix.Edits.size())
@@ -176,7 +175,7 @@ TEST(DiagnosticsTest, ToLSP) {
F.Message = "do something";
D.Fixes.push_back(F);
- auto MatchingLSP = [](const DiagBase &D, llvm::StringRef Message) {
+ auto MatchingLSP = [](const DiagBase &D, StringRef Message) {
clangd::Diagnostic Res;
Res.range = D.Range;
Res.severity = getSeverity(D.Severity);
@@ -199,8 +198,7 @@ main.cpp:2:3: error: something terrible
// Transform dianostics and check the results.
std::vector<std::pair<clangd::Diagnostic, std::vector<clangd::Fix>>> LSPDiags;
- toLSPDiags(D, [&](clangd::Diagnostic LSPDiag,
- llvm::ArrayRef<clangd::Fix> Fixes) {
+ toLSPDiags(D, [&](clangd::Diagnostic LSPDiag, ArrayRef<clangd::Fix> Fixes) {
LSPDiags.push_back({std::move(LSPDiag),
std::vector<clangd::Fix>(Fixes.begin(), Fixes.end())});
});
Modified: clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp Sat Oct 20 08:30:37 2018
@@ -24,11 +24,11 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
-using namespace llvm;
using ::testing::AllOf;
using ::testing::Contains;
using ::testing::Each;
@@ -151,7 +151,7 @@ Symbol sym(StringRef QName, index::Symbo
Symbol Sym;
std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
size_t Pos = QName.rfind("::");
- if (Pos == llvm::StringRef::npos) {
+ if (Pos == StringRef::npos) {
Sym.Name = QName;
Sym.Scope = "";
} else {
@@ -567,7 +567,7 @@ TEST(CompletionTest, IncludeInsertionPre
MockFSProvider FS;
MockCompilationDatabase CDB;
std::string Subdir = testPath("sub");
- std::string SearchDirArg = (llvm::Twine("-I") + Subdir).str();
+ std::string SearchDirArg = (Twine("-I") + Subdir).str();
CDB.ExtraClangFlags = {SearchDirArg.c_str()};
std::string BarHeader = testPath("sub/bar.h");
FS.Files[BarHeader] = "";
@@ -985,19 +985,18 @@ TEST(SignatureHelpTest, OpeningParen) {
class IndexRequestCollector : public SymbolIndex {
public:
- bool
- fuzzyFind(const FuzzyFindRequest &Req,
- llvm::function_ref<void(const Symbol &)> Callback) const override {
+ bool fuzzyFind(const FuzzyFindRequest &Req,
+ function_ref<void(const Symbol &)> Callback) const override {
std::lock_guard<std::mutex> Lock(Mut);
Requests.push_back(Req);
return true;
}
void lookup(const LookupRequest &,
- llvm::function_ref<void(const Symbol &)>) const override {}
+ function_ref<void(const Symbol &)>) const override {}
void refs(const RefsRequest &,
- llvm::function_ref<void(const Ref &)>) const override {}
+ function_ref<void(const Ref &)>) const override {}
// This is incorrect, but IndexRequestCollector is not an actual index and it
// isn't used in production code.
@@ -1016,7 +1015,7 @@ private:
mutable std::vector<FuzzyFindRequest> Requests;
};
-std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code) {
+std::vector<FuzzyFindRequest> captureIndexRequests(StringRef Code) {
clangd::CodeCompleteOptions Opts;
IndexRequestCollector Requests;
Opts.Index = &Requests;
@@ -2099,7 +2098,7 @@ TEST(CompletionTest, IncludedCompletionK
MockFSProvider FS;
MockCompilationDatabase CDB;
std::string Subdir = testPath("sub");
- std::string SearchDirArg = (llvm::Twine("-I") + Subdir).str();
+ std::string SearchDirArg = (Twine("-I") + Subdir).str();
CDB.ExtraClangFlags = {SearchDirArg.c_str()};
std::string BarHeader = testPath("sub/bar.h");
FS.Files[BarHeader] = "";
Modified: clang-tools-extra/trunk/unittests/clangd/DexTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/DexTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/DexTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/DexTests.cpp Sat Oct 20 08:30:37 2018
@@ -26,8 +26,8 @@
using ::testing::AnyOf;
using ::testing::ElementsAre;
using ::testing::UnorderedElementsAre;
-using namespace llvm;
+using namespace llvm;
namespace clang {
namespace clangd {
namespace dex {
@@ -250,17 +250,17 @@ TEST(DexIterators, StringRepresentation)
// No token given, prints full posting list.
auto I1 = L1.iterator();
- EXPECT_EQ(llvm::to_string(*I1), "[1 3 5]");
+ EXPECT_EQ(to_string(*I1), "[1 3 5]");
// Token given, uses token's string representation.
Token Tok(Token::Kind::Trigram, "L2");
auto I2 = L1.iterator(&Tok);
- EXPECT_EQ(llvm::to_string(*I2), "T=L2");
+ EXPECT_EQ(to_string(*I2), "T=L2");
auto Tree = C.limit(C.intersect(move(I1), move(I2)), 10);
// AND reorders its children, we don't care which order it prints.
- EXPECT_THAT(llvm::to_string(*Tree), AnyOf("(LIMIT 10 (& [1 3 5] T=L2))",
- "(LIMIT 10 (& T=L2 [1 3 5]))"));
+ EXPECT_THAT(to_string(*Tree), AnyOf("(LIMIT 10 (& [1 3 5] T=L2))",
+ "(LIMIT 10 (& T=L2 [1 3 5]))"));
}
TEST(DexIterators, Limit) {
@@ -325,28 +325,27 @@ TEST(DexIterators, Optimizations) {
const PostingList L3{3};
// empty and/or yield true/false
- EXPECT_EQ(llvm::to_string(*C.intersect()), "true");
- EXPECT_EQ(llvm::to_string(*C.unionOf()), "false");
+ EXPECT_EQ(to_string(*C.intersect()), "true");
+ EXPECT_EQ(to_string(*C.unionOf()), "false");
// true/false inside and/or short-circuit
- EXPECT_EQ(llvm::to_string(*C.intersect(L1.iterator(), C.all())), "[1]");
- EXPECT_EQ(llvm::to_string(*C.intersect(L1.iterator(), C.none())), "false");
+ EXPECT_EQ(to_string(*C.intersect(L1.iterator(), C.all())), "[1]");
+ EXPECT_EQ(to_string(*C.intersect(L1.iterator(), C.none())), "false");
// Not optimized to avoid breaking boosts.
- EXPECT_EQ(llvm::to_string(*C.unionOf(L1.iterator(), C.all())),
- "(| [1] true)");
- EXPECT_EQ(llvm::to_string(*C.unionOf(L1.iterator(), C.none())), "[1]");
+ EXPECT_EQ(to_string(*C.unionOf(L1.iterator(), C.all())), "(| [1] true)");
+ EXPECT_EQ(to_string(*C.unionOf(L1.iterator(), C.none())), "[1]");
// and/or nested inside and/or are flattened
- EXPECT_EQ(llvm::to_string(*C.intersect(
- L1.iterator(), C.intersect(L1.iterator(), L1.iterator()))),
+ EXPECT_EQ(to_string(*C.intersect(L1.iterator(),
+ C.intersect(L1.iterator(), L1.iterator()))),
"(& [1] [1] [1])");
- EXPECT_EQ(llvm::to_string(*C.unionOf(
- L1.iterator(), C.unionOf(L2.iterator(), L3.iterator()))),
+ EXPECT_EQ(to_string(*C.unionOf(L1.iterator(),
+ C.unionOf(L2.iterator(), L3.iterator()))),
"(| [1] [2] [3])");
// optimizations combine over multiple levels
- EXPECT_EQ(llvm::to_string(*C.intersect(
- C.intersect(L1.iterator(), C.intersect()), C.unionOf(C.all()))),
+ EXPECT_EQ(to_string(*C.intersect(C.intersect(L1.iterator(), C.intersect()),
+ C.unionOf(C.all()))),
"[1]");
}
Modified: clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp Sat Oct 20 08:30:37 2018
@@ -13,6 +13,7 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -23,18 +24,18 @@ struct IncrementalTestStep {
};
int rangeLength(StringRef Code, const Range &Rng) {
- llvm::Expected<size_t> Start = positionToOffset(Code, Rng.start);
- llvm::Expected<size_t> End = positionToOffset(Code, Rng.end);
+ Expected<size_t> Start = positionToOffset(Code, Rng.start);
+ Expected<size_t> End = positionToOffset(Code, Rng.end);
assert(Start);
assert(End);
return *End - *Start;
}
/// Send the changes one by one to updateDraft, verify the intermediate results.
-void stepByStep(llvm::ArrayRef<IncrementalTestStep> Steps) {
+void stepByStep(ArrayRef<IncrementalTestStep> Steps) {
DraftStore DS;
Annotations InitialSrc(Steps.front().Src);
- constexpr llvm::StringLiteral Path("/hello.cpp");
+ constexpr StringLiteral Path("/hello.cpp");
// Set the initial content.
DS.addDraft(Path, InitialSrc.code());
@@ -49,7 +50,7 @@ void stepByStep(llvm::ArrayRef<Increment
Contents.str(),
};
- llvm::Expected<std::string> Result = DS.updateDraft(Path, {Event});
+ Expected<std::string> Result = DS.updateDraft(Path, {Event});
ASSERT_TRUE(!!Result);
EXPECT_EQ(*Result, SrcAfter.code());
EXPECT_EQ(*DS.getDraft(Path), SrcAfter.code());
@@ -57,11 +58,11 @@ void stepByStep(llvm::ArrayRef<Increment
}
/// Send all the changes at once to updateDraft, check only the final result.
-void allAtOnce(llvm::ArrayRef<IncrementalTestStep> Steps) {
+void allAtOnce(ArrayRef<IncrementalTestStep> Steps) {
DraftStore DS;
Annotations InitialSrc(Steps.front().Src);
Annotations FinalSrc(Steps.back().Src);
- constexpr llvm::StringLiteral Path("/hello.cpp");
+ constexpr StringLiteral Path("/hello.cpp");
std::vector<TextDocumentContentChangeEvent> Changes;
for (size_t i = 0; i < Steps.size() - 1; i++) {
@@ -78,9 +79,9 @@ void allAtOnce(llvm::ArrayRef<Incrementa
// Set the initial content.
DS.addDraft(Path, InitialSrc.code());
- llvm::Expected<std::string> Result = DS.updateDraft(Path, Changes);
+ Expected<std::string> Result = DS.updateDraft(Path, Changes);
- ASSERT_TRUE(!!Result) << llvm::toString(Result.takeError());
+ ASSERT_TRUE(!!Result) << toString(Result.takeError());
EXPECT_EQ(*Result, FinalSrc.code());
EXPECT_EQ(*DS.getDraft(Path), FinalSrc.code());
}
@@ -195,11 +196,11 @@ TEST(DraftStoreIncrementalUpdateTest, Wr
Change.range->end.character = 2;
Change.rangeLength = 10;
- llvm::Expected<std::string> Result = DS.updateDraft(File, {Change});
+ Expected<std::string> Result = DS.updateDraft(File, {Change});
EXPECT_TRUE(!Result);
EXPECT_EQ(
- llvm::toString(Result.takeError()),
+ toString(Result.takeError()),
"Change's rangeLength (10) doesn't match the computed range length (2).");
}
@@ -216,10 +217,10 @@ TEST(DraftStoreIncrementalUpdateTest, En
Change.range->end.line = 0;
Change.range->end.character = 3;
- llvm::Expected<std::string> Result = DS.updateDraft(File, {Change});
+ Expected<std::string> Result = DS.updateDraft(File, {Change});
EXPECT_TRUE(!Result);
- EXPECT_EQ(llvm::toString(Result.takeError()),
+ EXPECT_EQ(toString(Result.takeError()),
"Range's end position (0:3) is before start position (0:5)");
}
@@ -237,10 +238,10 @@ TEST(DraftStoreIncrementalUpdateTest, St
Change.range->end.character = 100;
Change.text = "foo";
- llvm::Expected<std::string> Result = DS.updateDraft(File, {Change});
+ Expected<std::string> Result = DS.updateDraft(File, {Change});
EXPECT_TRUE(!Result);
- EXPECT_EQ(llvm::toString(Result.takeError()),
+ EXPECT_EQ(toString(Result.takeError()),
"UTF-16 offset 100 is invalid for line 0");
}
@@ -258,10 +259,10 @@ TEST(DraftStoreIncrementalUpdateTest, En
Change.range->end.character = 100;
Change.text = "foo";
- llvm::Expected<std::string> Result = DS.updateDraft(File, {Change});
+ Expected<std::string> Result = DS.updateDraft(File, {Change});
EXPECT_TRUE(!Result);
- EXPECT_EQ(llvm::toString(Result.takeError()),
+ EXPECT_EQ(toString(Result.takeError()),
"UTF-16 offset 100 is invalid for line 0");
}
@@ -279,11 +280,10 @@ TEST(DraftStoreIncrementalUpdateTest, St
Change.range->end.character = 0;
Change.text = "foo";
- llvm::Expected<std::string> Result = DS.updateDraft(File, {Change});
+ Expected<std::string> Result = DS.updateDraft(File, {Change});
EXPECT_TRUE(!Result);
- EXPECT_EQ(llvm::toString(Result.takeError()),
- "Line value is out of range (100)");
+ EXPECT_EQ(toString(Result.takeError()), "Line value is out of range (100)");
}
TEST(DraftStoreIncrementalUpdateTest, EndLineOutOfRange) {
@@ -300,11 +300,10 @@ TEST(DraftStoreIncrementalUpdateTest, En
Change.range->end.character = 0;
Change.text = "foo";
- llvm::Expected<std::string> Result = DS.updateDraft(File, {Change});
+ Expected<std::string> Result = DS.updateDraft(File, {Change});
EXPECT_TRUE(!Result);
- EXPECT_EQ(llvm::toString(Result.takeError()),
- "Line value is out of range (100)");
+ EXPECT_EQ(toString(Result.takeError()), "Line value is out of range (100)");
}
/// Check that if a valid change is followed by an invalid change, the original
@@ -334,13 +333,13 @@ TEST(DraftStoreIncrementalUpdateTest, In
Change2.range->end.character = 100;
Change2.text = "something";
- llvm::Expected<std::string> Result = DS.updateDraft(File, {Change1, Change2});
+ Expected<std::string> Result = DS.updateDraft(File, {Change1, Change2});
EXPECT_TRUE(!Result);
- EXPECT_EQ(llvm::toString(Result.takeError()),
+ EXPECT_EQ(toString(Result.takeError()),
"UTF-16 offset 100 is invalid for line 0");
- llvm::Optional<std::string> Contents = DS.getDraft(File);
+ Optional<std::string> Contents = DS.getDraft(File);
EXPECT_TRUE(Contents);
EXPECT_EQ(*Contents, OriginalContents);
}
Modified: clang-tools-extra/trunk/unittests/clangd/FSTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/FSTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/FSTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/FSTests.cpp Sat Oct 20 08:30:37 2018
@@ -12,12 +12,13 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
TEST(FSTests, PreambleStatusCache) {
- llvm::StringMap<std::string> Files;
+ StringMap<std::string> Files;
Files["x"] = "";
Files["y"] = "";
Files["main"] = "";
@@ -35,10 +36,9 @@ TEST(FSTests, PreambleStatusCache) {
// Main file is not cached.
EXPECT_FALSE(StatCache.lookup(testPath("main")).hasValue());
- llvm::vfs::Status S("fake", llvm::sys::fs::UniqueID(0, 0),
- std::chrono::system_clock::now(), 0, 0, 1024,
- llvm::sys::fs::file_type::regular_file,
- llvm::sys::fs::all_all);
+ vfs::Status S("fake", sys::fs::UniqueID(0, 0),
+ std::chrono::system_clock::now(), 0, 0, 1024,
+ sys::fs::file_type::regular_file, sys::fs::all_all);
StatCache.update(*FS, S);
auto ConsumeFS = StatCache.getConsumingFS(FS);
auto Cached = ConsumeFS->status(testPath("fake"));
Modified: clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp Sat Oct 20 08:30:37 2018
@@ -41,6 +41,7 @@ MATCHER_P(FileURI, F, "") { return arg.L
MATCHER_P(DeclURI, U, "") { return arg.CanonicalDeclaration.FileURI == U; }
MATCHER_P(QName, N, "") { return (arg.Scope + arg.Name).str() == N; }
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -49,7 +50,7 @@ RefsAre(std::vector<testing::Matcher<Ref
return ElementsAre(testing::Pair(_, UnorderedElementsAreArray(Matchers)));
}
-Symbol symbol(llvm::StringRef ID) {
+Symbol symbol(StringRef ID) {
Symbol Sym;
Sym.ID = SymbolID(ID);
Sym.Name = ID;
@@ -63,7 +64,7 @@ std::unique_ptr<SymbolSlab> numSlab(int
return llvm::make_unique<SymbolSlab>(std::move(Slab).build());
}
-std::unique_ptr<RefSlab> refSlab(const SymbolID &ID, llvm::StringRef Path) {
+std::unique_ptr<RefSlab> refSlab(const SymbolID &ID, StringRef Path) {
RefSlab::Builder Slab;
Ref R;
R.Location.FileURI = Path;
@@ -123,7 +124,7 @@ TEST(FileSymbolsTest, SnapshotAliveAfter
}
// Adds Basename.cpp, which includes Basename.h, which contains Code.
-void update(FileIndex &M, llvm::StringRef Basename, llvm::StringRef Code) {
+void update(FileIndex &M, StringRef Basename, StringRef Code) {
TestTU File;
File.Filename = (Basename + ".cpp").str();
File.HeaderFilename = (Basename + ".h").str();
@@ -228,7 +229,7 @@ TEST(FileIndexTest, RebuildWithPreamble)
PI.CompileCommand.Filename = FooCpp;
PI.CompileCommand.CommandLine = {"clang", "-xc++", FooCpp};
- llvm::StringMap<std::string> Files;
+ StringMap<std::string> Files;
Files[FooCpp] = "";
Files[FooH] = R"cpp(
namespace ns_in_header {
@@ -343,11 +344,10 @@ TEST(FileIndexTest, ReferencesInMainFile
std::make_shared<PCHContainerOperations>(), /*StoreInMemory=*/true,
[&](ASTContext &Ctx, std::shared_ptr<Preprocessor> PP) {});
// Build AST for main file with preamble.
- auto AST = ParsedAST::build(
- createInvocationFromCommandLine(Cmd), PreambleData,
- llvm::MemoryBuffer::getMemBufferCopy(Main.code()),
- std::make_shared<PCHContainerOperations>(),
- PI.FS);
+ auto AST =
+ ParsedAST::build(createInvocationFromCommandLine(Cmd), PreambleData,
+ MemoryBuffer::getMemBufferCopy(Main.code()),
+ std::make_shared<PCHContainerOperations>(), PI.FS);
ASSERT_TRUE(AST);
FileIndex Index;
Index.updateMain(MainFile, *AST);
Modified: clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp Sat Oct 20 08:30:37 2018
@@ -13,10 +13,10 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
-using namespace llvm;
using testing::Not;
struct ExpectedMatch {
@@ -208,7 +208,7 @@ struct RankMatcher : public testing::Mat
Ok = false;
} else {
std::string Buf;
- llvm::raw_string_ostream Info(Buf);
+ raw_string_ostream Info(Buf);
auto AnnotatedMatch = Matcher.dumpLast(Info);
if (!Str.accepts(AnnotatedMatch)) {
Modified: clang-tools-extra/trunk/unittests/clangd/GlobalCompilationDatabaseTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/GlobalCompilationDatabaseTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/GlobalCompilationDatabaseTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/GlobalCompilationDatabaseTests.cpp Sat Oct 20 08:30:37 2018
@@ -14,13 +14,14 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
using ::testing::ElementsAre;
TEST(GlobalCompilationDatabaseTest, FallbackCommand) {
- DirectoryBasedGlobalCompilationDatabase DB(llvm::None);
+ DirectoryBasedGlobalCompilationDatabase DB(None);
auto Cmd = DB.getFallbackCommand(testPath("foo/bar.cc"));
EXPECT_EQ(Cmd.Directory, testPath("foo"));
EXPECT_THAT(Cmd.CommandLine, ElementsAre("clang", testPath("foo/bar.cc")));
Modified: clang-tools-extra/trunk/unittests/clangd/HeadersTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/HeadersTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/HeadersTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/HeadersTests.cpp Sat Oct 20 08:30:37 2018
@@ -18,6 +18,7 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -56,7 +57,7 @@ private:
CI->getDiagnosticOpts().IgnoreWarnings = true;
auto Clang = prepareCompilerInstance(
std::move(CI), /*Preamble=*/nullptr,
- llvm::MemoryBuffer::getMemBuffer(FS.Files[MainFile], MainFile),
+ MemoryBuffer::getMemBuffer(FS.Files[MainFile], MainFile),
std::make_shared<PCHContainerOperations>(), VFS, IgnoreDiags);
EXPECT_FALSE(Clang->getFrontendOpts().Inputs.empty());
@@ -88,9 +89,9 @@ protected:
if (Preferred.empty())
Preferred = Original;
- auto ToHeaderFile = [](llvm::StringRef Header) {
+ auto ToHeaderFile = [](StringRef Header) {
return HeaderFile{Header,
- /*Verbatim=*/!llvm::sys::path::is_absolute(Header)};
+ /*Verbatim=*/!sys::path::is_absolute(Header)};
};
IncludeInserter Inserter(MainFile, /*Code=*/"", format::getLLVMStyle(),
@@ -125,7 +126,7 @@ protected:
MockCompilationDatabase CDB;
std::string MainFile = testPath("main.cpp");
std::string Subdir = testPath("sub");
- std::string SearchDirArg = (llvm::Twine("-I") + Subdir).str();
+ std::string SearchDirArg = (Twine("-I") + Subdir).str();
IgnoringDiagConsumer IgnoreDiags;
};
@@ -237,7 +238,7 @@ TEST_F(HeadersTest, DontInsertDuplicateR
TEST_F(HeadersTest, PreferInserted) {
auto Edit = insert("<y>");
EXPECT_TRUE(Edit.hasValue());
- EXPECT_TRUE(llvm::StringRef(Edit->newText).contains("<y>"));
+ EXPECT_TRUE(StringRef(Edit->newText).contains("<y>"));
}
} // namespace
Modified: clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp Sat Oct 20 08:30:37 2018
@@ -23,8 +23,8 @@ using testing::ElementsAre;
using testing::Pair;
using testing::Pointee;
using testing::UnorderedElementsAre;
-using namespace llvm;
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
Modified: clang-tools-extra/trunk/unittests/clangd/JSONTransportTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/JSONTransportTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/JSONTransportTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/JSONTransportTests.cpp Sat Oct 20 08:30:37 2018
@@ -24,7 +24,7 @@ namespace {
// Fixture takes care of managing the input/output buffers for the transport.
class JSONTransportTest : public ::testing::Test {
std::string InBuf, OutBuf, MirrorBuf;
- llvm::raw_string_ostream Out, Mirror;
+ raw_string_ostream Out, Mirror;
std::unique_ptr<FILE, int (*)(FILE *)> In;
protected:
@@ -78,8 +78,8 @@ public:
if (Params)
Log << "Reply(" << ID << "): " << *Params << "\n";
else
- Log << "Reply(" << ID
- << "): error = " << llvm::toString(Params.takeError()) << "\n";
+ Log << "Reply(" << ID << "): error = " << toString(Params.takeError())
+ << "\n";
return true;
}
};
@@ -104,7 +104,7 @@ TEST_F(JSONTransportTest, StandardDense)
/*Pretty=*/false, JSONStreamStyle::Standard);
Echo E(*T);
auto Err = T->loop(E);
- EXPECT_FALSE(bool(Err)) << llvm::toString(std::move(Err));
+ EXPECT_FALSE(bool(Err)) << toString(std::move(Err));
const char *WantLog = R"(
Notification call: 1234
@@ -145,7 +145,7 @@ TEST_F(JSONTransportTest, DelimitedPrett
/*Pretty=*/true, JSONStreamStyle::Delimited);
Echo E(*T);
auto Err = T->loop(E);
- EXPECT_FALSE(bool(Err)) << llvm::toString(std::move(Err));
+ EXPECT_FALSE(bool(Err)) << toString(std::move(Err));
const char *WantLog = R"(
Notification call: 1234
Modified: clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp Sat Oct 20 08:30:37 2018
@@ -30,6 +30,7 @@
#include "gtest/gtest.h"
#include <vector>
+using namespace llvm;
namespace clang {
namespace clangd {
@@ -251,7 +252,7 @@ TEST(QualityTests, SymbolRelevanceSignal
SymbolRelevanceSignals IndexProximate;
IndexProximate.SymbolURI = "unittest:/foo/bar.h";
- llvm::StringMap<SourceParams> ProxSources;
+ StringMap<SourceParams> ProxSources;
ProxSources.try_emplace(testPath("foo/baz.h"));
URIDistance Distance(ProxSources);
IndexProximate.FileProximityMatch = &Distance;
@@ -335,7 +336,7 @@ TEST(QualityTests, NoBoostForClassConstr
const NamedDecl *CtorDecl = &findAnyDecl(AST, [](const NamedDecl &ND) {
return (ND.getQualifiedNameAsString() == "Foo::Foo") &&
- llvm::isa<CXXConstructorDecl>(&ND);
+ isa<CXXConstructorDecl>(&ND);
});
SymbolRelevanceSignals Ctor;
Ctor.merge(CodeCompletionResult(CtorDecl, /*Priority=*/0));
@@ -397,7 +398,7 @@ TEST(QualityTests, ConstructorQuality) {
const NamedDecl *CtorDecl = &findAnyDecl(AST, [](const NamedDecl &ND) {
return (ND.getQualifiedNameAsString() == "Foo::Foo") &&
- llvm::isa<CXXConstructorDecl>(&ND);
+ isa<CXXConstructorDecl>(&ND);
});
SymbolQualitySignals Q;
Modified: clang-tools-extra/trunk/unittests/clangd/RIFFTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/RIFFTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/RIFFTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/RIFFTests.cpp Sat Oct 20 08:30:37 2018
@@ -11,10 +11,10 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
-using namespace llvm;
using ::testing::ElementsAre;
TEST(RIFFTest, File) {
@@ -28,7 +28,7 @@ TEST(RIFFTest, File) {
"oddd\x05\0\0\0abcde\0",
38);
- EXPECT_EQ(llvm::to_string(File), Serialized);
+ EXPECT_EQ(to_string(File), Serialized);
auto Parsed = riff::readFile(Serialized);
ASSERT_TRUE(bool(Parsed)) << Parsed.takeError();
EXPECT_EQ(*Parsed, File);
Modified: clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp Sat Oct 20 08:30:37 2018
@@ -18,6 +18,8 @@ using testing::AllOf;
using testing::Pair;
using testing::UnorderedElementsAre;
using testing::UnorderedElementsAreArray;
+
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -156,7 +158,7 @@ TEST(SerializationTest, BinaryConversion
// Write to binary format, and parse again.
IndexFileOut Out(*In);
Out.Format = IndexFileFormat::RIFF;
- std::string Serialized = llvm::to_string(Out);
+ std::string Serialized = to_string(Out);
auto In2 = readIndexFile(Serialized);
ASSERT_TRUE(bool(In2)) << In.takeError();
Modified: clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp Sat Oct 20 08:30:37 2018
@@ -13,13 +13,11 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
-namespace clang{
+using namespace llvm;
+namespace clang {
namespace clangd {
namespace {
-using llvm::Failed;
-using llvm::HasValue;
-
MATCHER_P2(Pos, Line, Col, "") {
return arg.line == Line && arg.character == Col;
}
Modified: clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp Sat Oct 20 08:30:37 2018
@@ -27,9 +27,9 @@
#include <memory>
#include <string>
+using namespace llvm;
namespace clang {
namespace clangd {
-
namespace {
using testing::_;
@@ -222,7 +222,7 @@ public:
class SymbolCollectorTest : public ::testing::Test {
public:
SymbolCollectorTest()
- : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem),
+ : InMemoryFileSystem(new vfs::InMemoryFileSystem),
TestHeaderName(testPath("symbol.h")),
TestFileName(testPath("symbol.cc")) {
TestHeaderURI = URI::createFile(TestHeaderName).toString();
@@ -231,7 +231,7 @@ public:
bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode,
const std::vector<std::string> &ExtraArgs = {}) {
- llvm::IntrusiveRefCntPtr<FileManager> Files(
+ IntrusiveRefCntPtr<FileManager> Files(
new FileManager(FileSystemOptions(), InMemoryFileSystem));
auto Factory = llvm::make_unique<SymbolIndexActionFactory>(
@@ -251,9 +251,9 @@ public:
std::make_shared<PCHContainerOperations>());
InMemoryFileSystem->addFile(TestHeaderName, 0,
- llvm::MemoryBuffer::getMemBuffer(HeaderCode));
+ MemoryBuffer::getMemBuffer(HeaderCode));
InMemoryFileSystem->addFile(TestFileName, 0,
- llvm::MemoryBuffer::getMemBuffer(MainCode));
+ MemoryBuffer::getMemBuffer(MainCode));
Invocation.run();
Symbols = Factory->Collector->takeSymbols();
Refs = Factory->Collector->takeRefs();
@@ -261,7 +261,7 @@ public:
}
protected:
- llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem;
+ IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem;
std::string TestHeaderName;
std::string TestHeaderURI;
std::string TestFileName;
@@ -848,7 +848,7 @@ TEST_F(SymbolCollectorTest, SkipIncFileW
auto IncFile = testPath("test.inc");
auto IncURI = URI::createFile(IncFile).toString();
InMemoryFileSystem->addFile(IncFile, 0,
- llvm::MemoryBuffer::getMemBuffer("class X {};"));
+ MemoryBuffer::getMemBuffer("class X {};"));
runSymbolCollector("#include \"test.inc\"\nclass Y {};", /*Main=*/"",
/*ExtraArgs=*/{"-I", testRoot()});
EXPECT_THAT(Symbols,
@@ -867,7 +867,7 @@ TEST_F(SymbolCollectorTest, MainFileIsHe
auto IncFile = testPath("test.inc");
auto IncURI = URI::createFile(IncFile).toString();
InMemoryFileSystem->addFile(IncFile, 0,
- llvm::MemoryBuffer::getMemBuffer("class X {};"));
+ MemoryBuffer::getMemBuffer("class X {};"));
runSymbolCollector("", /*Main=*/"#include \"test.inc\"",
/*ExtraArgs=*/{"-I", testRoot()});
EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(QName("X"), DeclURI(IncURI),
@@ -883,7 +883,7 @@ TEST_F(SymbolCollectorTest, MainFileIsHe
auto IncFile = testPath("test.inc");
auto IncURI = URI::createFile(IncFile).toString();
InMemoryFileSystem->addFile(IncFile, 0,
- llvm::MemoryBuffer::getMemBuffer("class X {};"));
+ MemoryBuffer::getMemBuffer("class X {};"));
runSymbolCollector("", /*Main=*/"#include \"test.inc\"",
/*ExtraArgs=*/{"-I", testRoot()});
EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(QName("X"), DeclURI(IncURI),
@@ -897,7 +897,7 @@ TEST_F(SymbolCollectorTest, FallbackToIn
auto IncFile = testPath("test.inc");
auto IncURI = URI::createFile(IncFile).toString();
InMemoryFileSystem->addFile(IncFile, 0,
- llvm::MemoryBuffer::getMemBuffer("class X {};"));
+ MemoryBuffer::getMemBuffer("class X {};"));
runSymbolCollector("", /*Main=*/"#include \"test.inc\"",
/*ExtraArgs=*/{"-I", testRoot()});
EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(QName("X"), DeclURI(IncURI),
Modified: clang-tools-extra/trunk/unittests/clangd/SyncAPI.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/SyncAPI.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/SyncAPI.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SyncAPI.cpp Sat Oct 20 08:30:37 2018
@@ -9,6 +9,7 @@
#include "SyncAPI.h"
+using namespace llvm;
namespace clang {
namespace clangd {
@@ -25,7 +26,7 @@ namespace {
/// T Result;
/// someAsyncFunc(Param1, Param2, /*Callback=*/capture(Result));
template <typename T> struct CaptureProxy {
- CaptureProxy(llvm::Optional<T> &Target) : Target(&Target) {
+ CaptureProxy(Optional<T> &Target) : Target(&Target) {
assert(!Target.hasValue());
}
@@ -37,7 +38,7 @@ template <typename T> struct CaptureProx
}
CaptureProxy &operator=(CaptureProxy &&) = delete;
- operator llvm::unique_function<void(T)>() && {
+ operator unique_function<void(T)>() && {
assert(!Future.valid() && "conversion to callback called multiple times");
Future = Promise.get_future();
return Bind(
@@ -56,7 +57,7 @@ template <typename T> struct CaptureProx
}
private:
- llvm::Optional<T> *Target;
+ Optional<T> *Target;
// Using shared_ptr to workaround compilation errors with MSVC.
// MSVC only allows default-construcitble and copyable objects as future<>
// arguments.
@@ -64,63 +65,63 @@ private:
std::future<std::shared_ptr<T>> Future;
};
-template <typename T> CaptureProxy<T> capture(llvm::Optional<T> &Target) {
+template <typename T> CaptureProxy<T> capture(Optional<T> &Target) {
return CaptureProxy<T>(Target);
}
} // namespace
-llvm::Expected<CodeCompleteResult>
-runCodeComplete(ClangdServer &Server, PathRef File, Position Pos,
- clangd::CodeCompleteOptions Opts) {
- llvm::Optional<llvm::Expected<CodeCompleteResult>> Result;
+Expected<CodeCompleteResult> runCodeComplete(ClangdServer &Server, PathRef File,
+ Position Pos,
+ clangd::CodeCompleteOptions Opts) {
+ Optional<Expected<CodeCompleteResult>> Result;
Server.codeComplete(File, Pos, Opts, capture(Result));
return std::move(*Result);
}
-llvm::Expected<SignatureHelp> runSignatureHelp(ClangdServer &Server,
- PathRef File, Position Pos) {
- llvm::Optional<llvm::Expected<SignatureHelp>> Result;
+Expected<SignatureHelp> runSignatureHelp(ClangdServer &Server, PathRef File,
+ Position Pos) {
+ Optional<Expected<SignatureHelp>> Result;
Server.signatureHelp(File, Pos, capture(Result));
return std::move(*Result);
}
-llvm::Expected<std::vector<Location>>
-runFindDefinitions(ClangdServer &Server, PathRef File, Position Pos) {
- llvm::Optional<llvm::Expected<std::vector<Location>>> Result;
+Expected<std::vector<Location>> runFindDefinitions(ClangdServer &Server,
+ PathRef File, Position Pos) {
+ Optional<Expected<std::vector<Location>>> Result;
Server.findDefinitions(File, Pos, capture(Result));
return std::move(*Result);
}
-llvm::Expected<std::vector<DocumentHighlight>>
+Expected<std::vector<DocumentHighlight>>
runFindDocumentHighlights(ClangdServer &Server, PathRef File, Position Pos) {
- llvm::Optional<llvm::Expected<std::vector<DocumentHighlight>>> Result;
+ Optional<Expected<std::vector<DocumentHighlight>>> Result;
Server.findDocumentHighlights(File, Pos, capture(Result));
return std::move(*Result);
}
-llvm::Expected<std::vector<tooling::Replacement>>
+Expected<std::vector<tooling::Replacement>>
runRename(ClangdServer &Server, PathRef File, Position Pos, StringRef NewName) {
- llvm::Optional<llvm::Expected<std::vector<tooling::Replacement>>> Result;
+ Optional<Expected<std::vector<tooling::Replacement>>> Result;
Server.rename(File, Pos, NewName, capture(Result));
return std::move(*Result);
}
std::string runDumpAST(ClangdServer &Server, PathRef File) {
- llvm::Optional<std::string> Result;
+ Optional<std::string> Result;
Server.dumpAST(File, capture(Result));
return std::move(*Result);
}
-llvm::Expected<std::vector<SymbolInformation>>
+Expected<std::vector<SymbolInformation>>
runWorkspaceSymbols(ClangdServer &Server, StringRef Query, int Limit) {
- llvm::Optional<llvm::Expected<std::vector<SymbolInformation>>> Result;
+ Optional<Expected<std::vector<SymbolInformation>>> Result;
Server.workspaceSymbols(Query, Limit, capture(Result));
return std::move(*Result);
}
-llvm::Expected<std::vector<SymbolInformation>>
+Expected<std::vector<SymbolInformation>>
runDocumentSymbols(ClangdServer &Server, PathRef File) {
- llvm::Optional<llvm::Expected<std::vector<SymbolInformation>>> Result;
+ Optional<Expected<std::vector<SymbolInformation>>> Result;
Server.documentSymbols(File, capture(Result));
return std::move(*Result);
}
Modified: clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp Sat Oct 20 08:30:37 2018
@@ -15,6 +15,7 @@
#include <algorithm>
#include <utility>
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
@@ -27,9 +28,9 @@ using ::testing::Pair;
using ::testing::Pointee;
using ::testing::UnorderedElementsAre;
-void ignoreUpdate(llvm::Optional<std::vector<Diag>>) {}
-void ignoreError(llvm::Error Err) {
- handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
+void ignoreUpdate(Optional<std::vector<Diag>>) {}
+void ignoreError(Error Err) {
+ handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
}
class TUSchedulerTests : public ::testing::Test {
@@ -39,8 +40,8 @@ protected:
buildTestFS(Files, Timestamps), std::move(Contents)};
}
- llvm::StringMap<std::string> Files;
- llvm::StringMap<time_t> Timestamps;
+ StringMap<std::string> Files;
+ StringMap<time_t> Timestamps;
MockCompilationDatabase CDB;
};
@@ -60,12 +61,12 @@ TEST_F(TUSchedulerTests, MissingFiles) {
// Assert each operation for missing file is an error (even if it's available
// in VFS).
- S.runWithAST("", Missing, [&](llvm::Expected<InputsAndAST> AST) {
+ S.runWithAST("", Missing, [&](Expected<InputsAndAST> AST) {
ASSERT_FALSE(bool(AST));
ignoreError(AST.takeError());
});
S.runWithPreamble("", Missing, TUScheduler::Stale,
- [&](llvm::Expected<InputsAndPreamble> Preamble) {
+ [&](Expected<InputsAndPreamble> Preamble) {
ASSERT_FALSE(bool(Preamble));
ignoreError(Preamble.takeError());
});
@@ -73,22 +74,21 @@ TEST_F(TUSchedulerTests, MissingFiles) {
S.remove(Missing);
// Assert there aren't any errors for added file.
- S.runWithAST("", Added, [&](llvm::Expected<InputsAndAST> AST) {
- EXPECT_TRUE(bool(AST));
- });
+ S.runWithAST("", Added,
+ [&](Expected<InputsAndAST> AST) { EXPECT_TRUE(bool(AST)); });
S.runWithPreamble("", Added, TUScheduler::Stale,
- [&](llvm::Expected<InputsAndPreamble> Preamble) {
+ [&](Expected<InputsAndPreamble> Preamble) {
EXPECT_TRUE(bool(Preamble));
});
S.remove(Added);
// Assert that all operations fail after removing the file.
- S.runWithAST("", Added, [&](llvm::Expected<InputsAndAST> AST) {
+ S.runWithAST("", Added, [&](Expected<InputsAndAST> AST) {
ASSERT_FALSE(bool(AST));
ignoreError(AST.takeError());
});
S.runWithPreamble("", Added, TUScheduler::Stale,
- [&](llvm::Expected<InputsAndPreamble> Preamble) {
+ [&](Expected<InputsAndPreamble> Preamble) {
ASSERT_FALSE(bool(Preamble));
ignoreError(Preamble.takeError());
});
@@ -190,7 +190,7 @@ TEST_F(TUSchedulerTests, PreambleConsist
[&](std::vector<Diag> Diags) {});
S.runWithPreamble("StaleRead", Path, TUScheduler::Stale,
- [&](llvm::Expected<InputsAndPreamble> Pre) {
+ [&](Expected<InputsAndPreamble> Pre) {
ASSERT_TRUE(bool(Pre));
assert(bool(Pre));
EXPECT_THAT(includes(Pre->Preamble),
@@ -199,7 +199,7 @@ TEST_F(TUSchedulerTests, PreambleConsist
++CallbackCount;
});
S.runWithPreamble("ConsistentRead", Path, TUScheduler::Consistent,
- [&](llvm::Expected<InputsAndPreamble> Pre) {
+ [&](Expected<InputsAndPreamble> Pre) {
ASSERT_TRUE(bool(Pre));
EXPECT_THAT(includes(Pre->Preamble),
ElementsAre("<B>"));
@@ -232,12 +232,11 @@ TEST_F(TUSchedulerTests, ManyUpdates) {
this->Files[Files.back()] = "";
}
- llvm::StringRef Contents1 = R"cpp(int a;)cpp";
- llvm::StringRef Contents2 = R"cpp(int main() { return 1; })cpp";
- llvm::StringRef Contents3 =
- R"cpp(int a; int b; int sum() { return a + b; })cpp";
+ StringRef Contents1 = R"cpp(int a;)cpp";
+ StringRef Contents2 = R"cpp(int main() { return 1; })cpp";
+ StringRef Contents3 = R"cpp(int a; int b; int sum() { return a + b; })cpp";
- llvm::StringRef AllContents[] = {Contents1, Contents2, Contents3};
+ StringRef AllContents[] = {Contents1, Contents2, Contents3};
const int AllContentsSize = 3;
// Scheduler may run tasks asynchronously, but should propagate the context.
@@ -256,7 +255,7 @@ TEST_F(TUSchedulerTests, ManyUpdates) {
WithContextValue WithNonce(NonceKey, ++Nonce);
S.update(File, Inputs, WantDiagnostics::Auto,
[File, Nonce, &Mut,
- &TotalUpdates](llvm::Optional<std::vector<Diag>> Diags) {
+ &TotalUpdates](Optional<std::vector<Diag>> Diags) {
EXPECT_THAT(Context::current().get(NonceKey),
Pointee(Nonce));
@@ -271,7 +270,7 @@ TEST_F(TUSchedulerTests, ManyUpdates) {
WithContextValue WithNonce(NonceKey, ++Nonce);
S.runWithAST("CheckAST", File,
[File, Inputs, Nonce, &Mut,
- &TotalASTReads](llvm::Expected<InputsAndAST> AST) {
+ &TotalASTReads](Expected<InputsAndAST> AST) {
EXPECT_THAT(Context::current().get(NonceKey),
Pointee(Nonce));
@@ -291,8 +290,8 @@ TEST_F(TUSchedulerTests, ManyUpdates) {
WithContextValue WithNonce(NonceKey, ++Nonce);
S.runWithPreamble(
"CheckPreamble", File, TUScheduler::Stale,
- [File, Inputs, Nonce, &Mut, &TotalPreambleReads](
- llvm::Expected<InputsAndPreamble> Preamble) {
+ [File, Inputs, Nonce, &Mut,
+ &TotalPreambleReads](Expected<InputsAndPreamble> Preamble) {
EXPECT_THAT(Context::current().get(NonceKey), Pointee(Nonce));
ASSERT_TRUE((bool)Preamble);
@@ -386,7 +385,7 @@ TEST_F(TUSchedulerTests, EmptyPreamble)
S.update(Foo, getInputs(Foo, WithPreamble), WantDiagnostics::Auto,
[](std::vector<Diag>) {});
S.runWithPreamble("getNonEmptyPreamble", Foo, TUScheduler::Stale,
- [&](llvm::Expected<InputsAndPreamble> Preamble) {
+ [&](Expected<InputsAndPreamble> Preamble) {
// We expect to get a non-empty preamble.
EXPECT_GT(cantFail(std::move(Preamble))
.Preamble->Preamble.getBounds()
@@ -402,7 +401,7 @@ TEST_F(TUSchedulerTests, EmptyPreamble)
// Wait for the preamble is being built.
ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
S.runWithPreamble("getEmptyPreamble", Foo, TUScheduler::Stale,
- [&](llvm::Expected<InputsAndPreamble> Preamble) {
+ [&](Expected<InputsAndPreamble> Preamble) {
// We expect to get an empty preamble.
EXPECT_EQ(cantFail(std::move(Preamble))
.Preamble->Preamble.getBounds()
@@ -434,7 +433,7 @@ TEST_F(TUSchedulerTests, RunWaitsForPrea
for (int I = 0; I < ReadsToSchedule; ++I) {
S.runWithPreamble(
"test", Foo, TUScheduler::Stale,
- [I, &PreamblesMut, &Preambles](llvm::Expected<InputsAndPreamble> IP) {
+ [I, &PreamblesMut, &Preambles](Expected<InputsAndPreamble> IP) {
std::lock_guard<std::mutex> Lock(PreamblesMut);
Preambles[I] = cantFail(std::move(IP)).Preamble;
});
@@ -511,7 +510,7 @@ TEST_F(TUSchedulerTests, NoChangeDiags)
S.update(FooCpp, getInputs(FooCpp, Contents), WantDiagnostics::No,
[](std::vector<Diag>) { ADD_FAILURE() << "Should not be called."; });
- S.runWithAST("touchAST", FooCpp, [](llvm::Expected<InputsAndAST> IA) {
+ S.runWithAST("touchAST", FooCpp, [](Expected<InputsAndAST> IA) {
// Make sure the AST was actually built.
cantFail(std::move(IA));
});
Modified: clang-tools-extra/trunk/unittests/clangd/TestFS.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/TestFS.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/TestFS.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TestFS.cpp Sat Oct 20 08:30:37 2018
@@ -19,8 +19,8 @@ namespace clangd {
using namespace llvm;
IntrusiveRefCntPtr<vfs::FileSystem>
-buildTestFS(llvm::StringMap<std::string> const &Files,
- llvm::StringMap<time_t> const &Timestamps) {
+buildTestFS(StringMap<std::string> const &Files,
+ StringMap<time_t> const &Timestamps) {
IntrusiveRefCntPtr<vfs::InMemoryFileSystem> MemFS(
new vfs::InMemoryFileSystem);
MemFS->setCurrentWorkingDirectory(testRoot());
@@ -56,7 +56,7 @@ MockCompilationDatabase::getCompileComma
} else {
// Build a relative path using RelPathPrefix.
SmallString<32> RelativeFilePath(RelPathPrefix);
- llvm::sys::path::append(RelativeFilePath, FileName);
+ sys::path::append(RelativeFilePath, FileName);
CommandLine.push_back(RelativeFilePath.str());
}
@@ -90,29 +90,26 @@ class TestScheme : public URIScheme {
public:
static const char *Scheme;
- llvm::Expected<std::string>
- getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
- llvm::StringRef HintPath) const override {
+ Expected<std::string> getAbsolutePath(StringRef /*Authority*/, StringRef Body,
+ StringRef HintPath) const override {
assert(HintPath.startswith(testRoot()));
if (!Body.consume_front("/"))
- return llvm::make_error<llvm::StringError>(
+ return make_error<StringError>(
"Body of an unittest: URI must start with '/'",
- llvm::inconvertibleErrorCode());
- llvm::SmallString<16> Path(Body.begin(), Body.end());
- llvm::sys::path::native(Path);
+ inconvertibleErrorCode());
+ SmallString<16> Path(Body.begin(), Body.end());
+ sys::path::native(Path);
return testPath(Path);
}
- llvm::Expected<URI>
- uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
- llvm::StringRef Body = AbsolutePath;
+ Expected<URI> uriFromAbsolutePath(StringRef AbsolutePath) const override {
+ StringRef Body = AbsolutePath;
if (!Body.consume_front(testRoot()))
- return llvm::make_error<llvm::StringError>(
- AbsolutePath + "does not start with " + testRoot(),
- llvm::inconvertibleErrorCode());
+ return make_error<StringError>(AbsolutePath + "does not start with " +
+ testRoot(),
+ inconvertibleErrorCode());
- return URI(Scheme, /*Authority=*/"",
- llvm::sys::path::convert_to_slash(Body));
+ return URI(Scheme, /*Authority=*/"", sys::path::convert_to_slash(Body));
}
};
Modified: clang-tools-extra/trunk/unittests/clangd/TestIndex.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/TestIndex.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/TestIndex.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TestIndex.cpp Sat Oct 20 08:30:37 2018
@@ -9,14 +9,15 @@
#include "TestIndex.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-Symbol symbol(llvm::StringRef QName) {
+Symbol symbol(StringRef QName) {
Symbol Sym;
Sym.ID = SymbolID(QName.str());
size_t Pos = QName.rfind("::");
- if (Pos == llvm::StringRef::npos) {
+ if (Pos == StringRef::npos) {
Sym.Name = QName;
Sym.Scope = "";
} else {
@@ -28,7 +29,7 @@ Symbol symbol(llvm::StringRef QName) {
SymbolSlab generateSymbols(std::vector<std::string> QualifiedNames) {
SymbolSlab::Builder Slab;
- for (llvm::StringRef QName : QualifiedNames)
+ for (StringRef QName : QualifiedNames)
Slab.insert(symbol(QName));
return std::move(Slab).build();
}
@@ -56,8 +57,7 @@ std::vector<std::string> match(const Sym
}
// Returns qualified names of symbols with any of IDs in the index.
-std::vector<std::string> lookup(const SymbolIndex &I,
- llvm::ArrayRef<SymbolID> IDs) {
+std::vector<std::string> lookup(const SymbolIndex &I, ArrayRef<SymbolID> IDs) {
LookupRequest Req;
Req.IDs.insert(IDs.begin(), IDs.end());
std::vector<std::string> Results;
Modified: clang-tools-extra/trunk/unittests/clangd/TestTU.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/TestTU.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/TestTU.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TestTU.cpp Sat Oct 20 08:30:37 2018
@@ -16,9 +16,9 @@
#include "clang/Frontend/PCHContainerOperations.h"
#include "clang/Frontend/Utils.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
ParsedAST TestTU::build() const {
std::string FullFilename = testPath(Filename),
@@ -57,7 +57,7 @@ std::unique_ptr<SymbolIndex> TestTU::ind
return std::move(Idx);
}
-const Symbol &findSymbol(const SymbolSlab &Slab, llvm::StringRef QName) {
+const Symbol &findSymbol(const SymbolSlab &Slab, StringRef QName) {
const Symbol *Result = nullptr;
for (const Symbol &S : Slab) {
if (QName != (S.Scope + S.Name).str())
@@ -78,13 +78,13 @@ const Symbol &findSymbol(const SymbolSla
return *Result;
}
-const NamedDecl &findDecl(ParsedAST &AST, llvm::StringRef QName) {
- llvm::SmallVector<llvm::StringRef, 4> Components;
+const NamedDecl &findDecl(ParsedAST &AST, StringRef QName) {
+ SmallVector<StringRef, 4> Components;
QName.split(Components, "::");
auto &Ctx = AST.getASTContext();
auto LookupDecl = [&Ctx](const DeclContext &Scope,
- llvm::StringRef Name) -> const NamedDecl & {
+ StringRef Name) -> const NamedDecl & {
auto LookupRes = Scope.lookup(DeclarationName(&Ctx.Idents.get(Name)));
assert(!LookupRes.empty() && "Lookup failed");
assert(LookupRes.size() == 1 && "Lookup returned multiple results");
@@ -103,7 +103,7 @@ const NamedDecl &findAnyDecl(ParsedAST &
std::function<bool(const NamedDecl &)> Callback) {
struct Visitor : RecursiveASTVisitor<Visitor> {
decltype(Callback) CB;
- llvm::SmallVector<const NamedDecl *, 1> Decls;
+ SmallVector<const NamedDecl *, 1> Decls;
bool VisitNamedDecl(const NamedDecl *ND) {
if (CB(*ND))
Decls.push_back(ND);
@@ -120,7 +120,7 @@ const NamedDecl &findAnyDecl(ParsedAST &
return *Visitor.Decls.front();
}
-const NamedDecl &findAnyDecl(ParsedAST &AST, llvm::StringRef Name) {
+const NamedDecl &findAnyDecl(ParsedAST &AST, StringRef Name) {
return findAnyDecl(AST, [Name](const NamedDecl &ND) {
if (auto *ID = ND.getIdentifier())
if (ID->getName() == Name)
Modified: clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp Sat Oct 20 08:30:37 2018
@@ -17,10 +17,10 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
namespace {
-using namespace llvm;
MATCHER_P(StringNode, Val, "") {
if (arg->getType() != yaml::Node::NK_Scalar) {
@@ -92,7 +92,7 @@ TEST(TraceTest, SmokeTest) {
// Check whether we expect thread name events on this platform.
SmallString<32> ThreadName;
- llvm::get_thread_name(ThreadName);
+ get_thread_name(ThreadName);
bool ThreadsHaveNames = !ThreadName.empty();
// We expect in order:
Modified: clang-tools-extra/trunk/unittests/clangd/URITests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/URITests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/URITests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/URITests.cpp Sat Oct 20 08:30:37 2018
@@ -12,6 +12,7 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
@@ -27,18 +28,17 @@ MATCHER_P(Scheme, S, "") { return arg.sc
MATCHER_P(Authority, A, "") { return arg.authority() == A; }
MATCHER_P(Body, B, "") { return arg.body() == B; }
-std::string createOrDie(llvm::StringRef AbsolutePath,
- llvm::StringRef Scheme = "file") {
+std::string createOrDie(StringRef AbsolutePath, StringRef Scheme = "file") {
auto Uri = URI::create(AbsolutePath, Scheme);
if (!Uri)
- llvm_unreachable(llvm::toString(Uri.takeError()).c_str());
+ llvm_unreachable(toString(Uri.takeError()).c_str());
return Uri->toString();
}
-URI parseOrDie(llvm::StringRef Uri) {
+URI parseOrDie(StringRef Uri) {
auto U = URI::parse(Uri);
if (!U)
- llvm_unreachable(llvm::toString(U.takeError()).c_str());
+ llvm_unreachable(toString(U.takeError()).c_str());
return *U;
}
@@ -60,10 +60,10 @@ TEST(PercentEncodingTest, Decode) {
EXPECT_EQ(parseOrDie("x:a:b%3bc").body(), "a:b;c");
}
-std::string resolveOrDie(const URI &U, llvm::StringRef HintPath = "") {
+std::string resolveOrDie(const URI &U, StringRef HintPath = "") {
auto Path = URI::resolve(U, HintPath);
if (!Path)
- llvm_unreachable(llvm::toString(Path.takeError()).c_str());
+ llvm_unreachable(toString(Path.takeError()).c_str());
return *Path;
}
@@ -77,9 +77,9 @@ TEST(URITest, Create) {
}
TEST(URITest, FailedCreate) {
- auto Fail = [](llvm::Expected<URI> U) {
+ auto Fail = [](Expected<URI> U) {
if (!U) {
- llvm::consumeError(U.takeError());
+ consumeError(U.takeError());
return true;
}
return false;
@@ -120,10 +120,10 @@ TEST(URITest, Parse) {
}
TEST(URITest, ParseFailed) {
- auto FailedParse = [](llvm::StringRef U) {
+ auto FailedParse = [](StringRef U) {
auto URI = URI::parse(U);
if (!URI) {
- llvm::consumeError(URI.takeError());
+ consumeError(URI.takeError());
return true;
}
return false;
@@ -160,10 +160,10 @@ TEST(URITest, Platform) {
}
TEST(URITest, ResolveFailed) {
- auto FailedResolve = [](llvm::StringRef Uri) {
+ auto FailedResolve = [](StringRef Uri) {
auto Path = URI::resolve(parseOrDie(Uri));
if (!Path) {
- llvm::consumeError(Path.takeError());
+ consumeError(Path.takeError());
return true;
}
return false;
Modified: clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp?rev=344850&r1=344849&r2=344850&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp Sat Oct 20 08:30:37 2018
@@ -21,11 +21,11 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+using namespace llvm;
namespace clang {
namespace clangd {
-using namespace llvm;
-
namespace {
+
using testing::ElementsAre;
using testing::Field;
using testing::IsEmpty;
@@ -374,7 +374,7 @@ int [[bar_not_preamble]];
// Make the compilation paths appear as ../src/foo.cpp in the compile
// commands.
SmallString<32> RelPathPrefix("..");
- llvm::sys::path::append(RelPathPrefix, "src");
+ sys::path::append(RelPathPrefix, "src");
std::string BuildDir = testPath("build");
MockCompilationDatabase CDB(BuildDir, RelPathPrefix);
@@ -1243,7 +1243,7 @@ TEST(FindReferences, NoQueryForLocalSymb
struct RecordingIndex : public MemIndex {
mutable Optional<DenseSet<SymbolID>> RefIDs;
void refs(const RefsRequest &Req,
- llvm::function_ref<void(const Ref &)>) const override {
+ function_ref<void(const Ref &)>) const override {
RefIDs = Req.IDs;
}
};
@@ -1267,9 +1267,9 @@ TEST(FindReferences, NoQueryForLocalSymb
auto AST = TestTU::withCode(File.code()).build();
findReferences(AST, File.point(), &Rec);
if (T.WantQuery)
- EXPECT_NE(Rec.RefIDs, llvm::None) << T.AnnotatedCode;
+ EXPECT_NE(Rec.RefIDs, None) << T.AnnotatedCode;
else
- EXPECT_EQ(Rec.RefIDs, llvm::None) << T.AnnotatedCode;
+ EXPECT_EQ(Rec.RefIDs, None) << T.AnnotatedCode;
}
}
More information about the cfe-commits
mailing list