54 changes: 27 additions & 27 deletions clang-tools-extra/clangd/ClangdUnit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
#include "llvm/Support/raw_ostream.h"
#include <algorithm>

using namespace llvm;
namespace clang {
namespace clangd {
namespace {
Expand All @@ -45,7 +44,7 @@ bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
const tooling::CompileCommand &RHS) {
// We don't check for Output, it should not matter to clangd.
return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
}

template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
Expand Down Expand Up @@ -80,8 +79,8 @@ class ClangdFrontendAction : public SyntaxOnlyAction {
std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }

protected:
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) override {
std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
}

Expand Down Expand Up @@ -179,12 +178,12 @@ class ReplayPreamble : private PPCallbacks {
if (Inc.Resolved != "")
File = SM.getFileManager().getFile(Inc.Resolved);

StringRef WrittenFilename =
StringRef(Inc.Written).drop_front().drop_back();
bool Angled = StringRef(Inc.Written).startswith("<");
llvm::StringRef WrittenFilename =
llvm::StringRef(Inc.Written).drop_front().drop_back();
bool Angled = llvm::StringRef(Inc.Written).startswith("<");

// Re-lex the #include directive to find its interesting parts.
StringRef Src = SM.getBufferData(SM.getMainFileID());
llvm::StringRef Src = SM.getBufferData(SM.getMainFileID());
Lexer RawLexer(SM.getLocForStartOfFile(SM.getMainFileID()), LangOpts,
Src.begin(), Src.begin() + Inc.HashOffset, Src.end());
Token HashTok, IncludeTok, FilenameTok;
Expand All @@ -205,7 +204,7 @@ class ReplayPreamble : private PPCallbacks {
if (File)
Delegate->FileSkipped(*File, FilenameTok, Inc.FileKind);
else {
SmallString<1> UnusedRecovery;
llvm::SmallString<1> UnusedRecovery;
Delegate->FileNotFound(WrittenFilename, UnusedRecovery);
}
}
Expand All @@ -220,16 +219,16 @@ class ReplayPreamble : private PPCallbacks {

} // namespace

void dumpAST(ParsedAST &AST, raw_ostream &OS) {
void dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
}

Optional<ParsedAST>
llvm::Optional<ParsedAST>
ParsedAST::build(std::unique_ptr<CompilerInvocation> CI,
std::shared_ptr<const PreambleData> Preamble,
std::unique_ptr<MemoryBuffer> Buffer,
std::unique_ptr<llvm::MemoryBuffer> Buffer,
std::shared_ptr<PCHContainerOperations> PCHs,
IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
assert(CI);
// Command-line parsing sets DisableFree to true by default, but we don't want
// to leak memory in clangd.
Expand Down Expand Up @@ -362,7 +361,7 @@ const Preprocessor &ParsedAST::getPreprocessor() const {
return Clang->getPreprocessor();
}

ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
llvm::ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
return LocalTopLevelDecls;
}

Expand Down Expand Up @@ -438,7 +437,7 @@ buildCompilerInvocation(const ParseInputs &Inputs) {
// FIXME(ibiryukov): store diagnostics from CommandLine when we start
// reporting them.
IgnoreDiagnostics IgnoreDiagnostics;
IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
llvm::IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
CompilerInstance::createDiagnostics(new DiagnosticOptions,
&IgnoreDiagnostics, false);
std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
Expand All @@ -460,15 +459,15 @@ buildPreamble(PathRef FileName, CompilerInvocation &CI,
PreambleParsedCallback PreambleCallback) {
// Note that we don't need to copy the input contents, preamble can live
// without those.
auto ContentsBuffer = MemoryBuffer::getMemBuffer(Inputs.Contents);
auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Inputs.Contents);
auto Bounds =
ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);

if (OldPreamble &&
compileCommandsAreEqual(Inputs.CompileCommand, OldCompileCommand) &&
OldPreamble->Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
Inputs.FS.get())) {
vlog("Reusing preamble for file {0}", Twine(FileName));
vlog("Reusing preamble for file {0}", llvm::Twine(FileName));
return OldPreamble;
}
vlog("Preamble for file {0} cannot be reused. Attempting to rebuild it.",
Expand All @@ -477,7 +476,7 @@ buildPreamble(PathRef FileName, CompilerInvocation &CI,
trace::Span Tracer("BuildPreamble");
SPAN_ATTACH(Tracer, "File", FileName);
StoreDiags PreambleDiagnostics;
IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
llvm::IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
&PreambleDiagnostics, false);

Expand All @@ -496,7 +495,7 @@ buildPreamble(PathRef FileName, CompilerInvocation &CI,
// dirs.
}

SmallString<32> AbsFileName(FileName);
llvm::SmallString<32> AbsFileName(FileName);
Inputs.FS->makeAbsolute(AbsFileName);
auto StatCache = llvm::make_unique<PreambleFileStatusCache>(AbsFileName);
auto BuiltPreamble = PrecompiledPreamble::Build(
Expand All @@ -520,11 +519,11 @@ buildPreamble(PathRef FileName, CompilerInvocation &CI,
}
}

Optional<ParsedAST> buildAST(PathRef FileName,
std::unique_ptr<CompilerInvocation> Invocation,
const ParseInputs &Inputs,
std::shared_ptr<const PreambleData> Preamble,
std::shared_ptr<PCHContainerOperations> PCHs) {
llvm::Optional<ParsedAST>
buildAST(PathRef FileName, std::unique_ptr<CompilerInvocation> Invocation,
const ParseInputs &Inputs,
std::shared_ptr<const PreambleData> Preamble,
std::shared_ptr<PCHContainerOperations> PCHs) {
trace::Span Tracer("BuildAST");
SPAN_ATTACH(Tracer, "File", FileName);

Expand All @@ -537,9 +536,10 @@ Optional<ParsedAST> buildAST(PathRef FileName,
// dirs.
}

return ParsedAST::build(
llvm::make_unique<CompilerInvocation>(*Invocation), Preamble,
MemoryBuffer::getMemBufferCopy(Inputs.Contents), PCHs, std::move(VFS));
return ParsedAST::build(llvm::make_unique<CompilerInvocation>(*Invocation),
Preamble,
llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents),
PCHs, std::move(VFS));
}

SourceLocation getBeginningOfIdentifier(ParsedAST &Unit, const Position &Pos,
Expand Down
138 changes: 72 additions & 66 deletions clang-tools-extra/clangd/CodeComplete.cpp

Large diffs are not rendered by default.

13 changes: 6 additions & 7 deletions clang-tools-extra/clangd/CodeCompletionStrings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,30 @@
#include "clang/Basic/SourceManager.h"
#include <utility>

using namespace llvm;
namespace clang {
namespace clangd {
namespace {

bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
return Chunk.Kind == CodeCompletionString::CK_Informative &&
StringRef(Chunk.Text).endswith("::");
llvm::StringRef(Chunk.Text).endswith("::");
}

void appendEscapeSnippet(const StringRef Text, std::string *Out) {
void appendEscapeSnippet(const llvm::StringRef Text, std::string *Out) {
for (const auto Character : Text) {
if (Character == '$' || Character == '}' || Character == '\\')
Out->push_back('\\');
Out->push_back(Character);
}
}

bool looksLikeDocComment(StringRef CommentText) {
bool looksLikeDocComment(llvm::StringRef CommentText) {
// We don't report comments that only contain "special" chars.
// This avoids reporting various delimiters, like:
// =================
// -----------------
// *****************
return CommentText.find_first_not_of("/*-= \t\r\n") != StringRef::npos;
return CommentText.find_first_not_of("/*-= \t\r\n") != llvm::StringRef::npos;
}

} // namespace
Expand Down Expand Up @@ -97,7 +96,7 @@ void getSignature(const CodeCompletionString &CCS, std::string *Signature,
// treat them carefully. For Objective-C methods, all typed-text chunks
// will end in ':' (unless there are no arguments, in which case we
// can safely treat them as C++).
if (!StringRef(Chunk.Text).endswith(":")) { // Treat as C++.
if (!llvm::StringRef(Chunk.Text).endswith(":")) { // Treat as C++.
if (RequiredQualifiers)
*RequiredQualifiers = std::move(*Signature);
Signature->clear();
Expand Down Expand Up @@ -171,7 +170,7 @@ void getSignature(const CodeCompletionString &CCS, std::string *Signature,
}

std::string formatDocumentation(const CodeCompletionString &CCS,
StringRef DocComment) {
llvm::StringRef DocComment) {
// Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
// information in the documentation field.
std::string Result;
Expand Down
19 changes: 10 additions & 9 deletions clang-tools-extra/clangd/Compiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,20 @@
#include "llvm/Support/Format.h"
#include "llvm/Support/FormatVariadic.h"

using namespace llvm;
namespace clang {
namespace clangd {

void IgnoreDiagnostics::log(DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &Info) {
// FIXME: format lazily, in case vlog is off.
SmallString<64> Message;
llvm::SmallString<64> Message;
Info.FormatDiagnostic(Message);

SmallString<64> Location;
llvm::SmallString<64> Location;
if (Info.hasSourceManager() && Info.getLocation().isValid()) {
auto &SourceMgr = Info.getSourceManager();
auto Loc = SourceMgr.getFileLoc(Info.getLocation());
raw_svector_ostream OS(Location);
llvm::raw_svector_ostream OS(Location);
Loc.print(OS, SourceMgr);
OS << ":";
}
Expand All @@ -41,11 +40,13 @@ void IgnoreDiagnostics::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
IgnoreDiagnostics::log(DiagLevel, Info);
}

std::unique_ptr<CompilerInstance> prepareCompilerInstance(
std::unique_ptr<clang::CompilerInvocation> CI,
const PrecompiledPreamble *Preamble, std::unique_ptr<MemoryBuffer> Buffer,
std::shared_ptr<PCHContainerOperations> PCHs,
IntrusiveRefCntPtr<vfs::FileSystem> VFS, DiagnosticConsumer &DiagsClient) {
std::unique_ptr<CompilerInstance>
prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,
const PrecompiledPreamble *Preamble,
std::unique_ptr<llvm::MemoryBuffer> Buffer,
std::shared_ptr<PCHContainerOperations> PCHs,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
DiagnosticConsumer &DiagsClient) {
assert(VFS && "VFS is null");
assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
"Setting RetainRemappedFileBuffers to true will cause a memory leak "
Expand Down
41 changes: 20 additions & 21 deletions clang-tools-extra/clangd/Diagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
#include "llvm/Support/Path.h"
#include <algorithm>

using namespace llvm;
namespace clang {
namespace clangd {

Expand Down Expand Up @@ -57,7 +56,7 @@ Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
if (locationInRange(Loc, R, M))
return halfOpenToRange(M, R);
}
Optional<Range> FallbackRange;
llvm::Optional<Range> FallbackRange;
// The range may be given as a fixit hint instead.
for (const auto &F : D.getFixItHints()) {
auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
Expand Down Expand Up @@ -93,7 +92,7 @@ bool isNote(DiagnosticsEngine::Level L) {
return L == DiagnosticsEngine::Note || L == DiagnosticsEngine::Remark;
}

StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
llvm::StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
switch (Lvl) {
case DiagnosticsEngine::Ignored:
return "ignored";
Expand Down Expand Up @@ -122,12 +121,12 @@ StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
///
/// dir1/dir2/dir3/../../dir4/header.h:12:23
/// error: undeclared identifier
void printDiag(raw_string_ostream &OS, const DiagBase &D) {
void printDiag(llvm::raw_string_ostream &OS, const DiagBase &D) {
if (D.InsideMainFile) {
// Paths to main files are often taken from compile_command.json, where they
// are typically absolute. To reduce noise we print only basename for them,
// it should not be confusing and saves space.
OS << sys::path::filename(D.File) << ":";
OS << llvm::sys::path::filename(D.File) << ":";
} else {
OS << D.File << ":";
}
Expand All @@ -147,7 +146,7 @@ void printDiag(raw_string_ostream &OS, const DiagBase &D) {
/// Capitalizes the first word in the diagnostic's message.
std::string capitalize(std::string Message) {
if (!Message.empty())
Message[0] = toUpper(Message[0]);
Message[0] = llvm::toUpper(Message[0]);
return Message;
}

Expand All @@ -165,7 +164,7 @@ std::string capitalize(std::string Message) {
/// note: candidate function not viable: requires 3 arguments
std::string mainMessage(const Diag &D) {
std::string Result;
raw_string_ostream OS(Result);
llvm::raw_string_ostream OS(Result);
OS << D.Message;
for (auto &Note : D.Notes) {
OS << "\n\n";
Expand All @@ -180,7 +179,7 @@ std::string mainMessage(const Diag &D) {
/// for the user to understand the note.
std::string noteMessage(const Diag &Main, const DiagBase &Note) {
std::string Result;
raw_string_ostream OS(Result);
llvm::raw_string_ostream OS(Result);
OS << Note.Message;
OS << "\n\n";
printDiag(OS, Main);
Expand All @@ -189,7 +188,7 @@ std::string noteMessage(const Diag &Main, const DiagBase &Note) {
}
} // namespace

raw_ostream &operator<<(raw_ostream &OS, const DiagBase &D) {
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const DiagBase &D) {
OS << "[";
if (!D.InsideMainFile)
OS << D.File << ":";
Expand All @@ -198,7 +197,7 @@ raw_ostream &operator<<(raw_ostream &OS, const DiagBase &D) {
return OS << D.Message;
}

raw_ostream &operator<<(raw_ostream &OS, const Fix &F) {
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Fix &F) {
OS << F.Message << " {";
const char *Sep = "";
for (const auto &Edit : F.Edits) {
Expand All @@ -208,7 +207,7 @@ raw_ostream &operator<<(raw_ostream &OS, const Fix &F) {
return OS << "}";
}

raw_ostream &operator<<(raw_ostream &OS, const Diag &D) {
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diag &D) {
OS << static_cast<const DiagBase &>(D);
if (!D.Notes.empty()) {
OS << ", notes: {";
Expand Down Expand Up @@ -240,9 +239,9 @@ CodeAction toCodeAction(const Fix &F, const URIForFile &File) {
return Action;
}

void toLSPDiags(const Diag &D, const URIForFile &File,
const ClangdDiagnosticOptions &Opts,
function_ref<void(clangd::Diagnostic, ArrayRef<Fix>)> OutFn) {
void toLSPDiags(
const Diag &D, const URIForFile &File, const ClangdDiagnosticOptions &Opts,
llvm::function_ref<void(clangd::Diagnostic, llvm::ArrayRef<Fix>)> OutFn) {
auto FillBasicFields = [](const DiagBase &D) -> clangd::Diagnostic {
clangd::Diagnostic Res;
Res.range = D.Range;
Expand All @@ -269,7 +268,7 @@ void toLSPDiags(const Diag &D, const URIForFile &File,
continue;
clangd::Diagnostic Res = FillBasicFields(Note);
Res.message = noteMessage(D, Note);
OutFn(std::move(Res), ArrayRef<Fix>());
OutFn(std::move(Res), llvm::ArrayRef<Fix>());
}
}

Expand Down Expand Up @@ -315,7 +314,7 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,

auto FillDiagBase = [&](DiagBase &D) {
D.Range = diagnosticRange(Info, *LangOpts);
SmallString<64> Message;
llvm::SmallString<64> Message;
Info.FormatDiagnostic(Message);
D.Message = Message.str();
D.InsideMainFile = InsideMainFile;
Expand All @@ -333,24 +332,24 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
if (!InsideMainFile)
return false;

SmallVector<TextEdit, 1> Edits;
llvm::SmallVector<TextEdit, 1> Edits;
for (auto &FixIt : Info.getFixItHints()) {
if (!isInsideMainFile(FixIt.RemoveRange.getBegin(),
Info.getSourceManager()))
return false;
Edits.push_back(toTextEdit(FixIt, Info.getSourceManager(), *LangOpts));
}

SmallString<64> Message;
llvm::SmallString<64> Message;
// If requested and possible, create a message like "change 'foo' to 'bar'".
if (SyntheticMessage && Info.getNumFixItHints() == 1) {
const auto &FixIt = Info.getFixItHint(0);
bool Invalid = false;
StringRef Remove = Lexer::getSourceText(
llvm::StringRef Remove = Lexer::getSourceText(
FixIt.RemoveRange, Info.getSourceManager(), *LangOpts, &Invalid);
StringRef Insert = FixIt.CodeToInsert;
llvm::StringRef Insert = FixIt.CodeToInsert;
if (!Invalid) {
raw_svector_ostream M(Message);
llvm::raw_svector_ostream M(Message);
if (!Remove.empty() && !Insert.empty())
M << "change '" << Remove << "' to '" << Insert << "'";
else if (!Remove.empty())
Expand Down
32 changes: 16 additions & 16 deletions clang-tools-extra/clangd/DraftStore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@
#include "SourceCode.h"
#include "llvm/Support/Errc.h"

using namespace llvm;
namespace clang {
namespace clangd {

Optional<std::string> DraftStore::getDraft(PathRef File) const {
llvm::Optional<std::string> DraftStore::getDraft(PathRef File) const {
std::lock_guard<std::mutex> Lock(Mutex);

auto It = Drafts.find(File);
Expand All @@ -35,20 +34,19 @@ std::vector<Path> DraftStore::getActiveFiles() const {
return ResultVector;
}

void DraftStore::addDraft(PathRef File, StringRef Contents) {
void DraftStore::addDraft(PathRef File, llvm::StringRef Contents) {
std::lock_guard<std::mutex> Lock(Mutex);

Drafts[File] = Contents;
}

Expected<std::string>
DraftStore::updateDraft(PathRef File,
ArrayRef<TextDocumentContentChangeEvent> Changes) {
llvm::Expected<std::string> DraftStore::updateDraft(
PathRef File, llvm::ArrayRef<TextDocumentContentChangeEvent> Changes) {
std::lock_guard<std::mutex> Lock(Mutex);

auto EntryIt = Drafts.find(File);
if (EntryIt == Drafts.end()) {
return make_error<StringError>(
return llvm::make_error<llvm::StringError>(
"Trying to do incremental update on non-added document: " + File,
llvm::errc::invalid_argument);
}
Expand All @@ -62,19 +60,21 @@ DraftStore::updateDraft(PathRef File,
}

const Position &Start = Change.range->start;
Expected<size_t> StartIndex = positionToOffset(Contents, Start, false);
llvm::Expected<size_t> StartIndex =
positionToOffset(Contents, Start, false);
if (!StartIndex)
return StartIndex.takeError();

const Position &End = Change.range->end;
Expected<size_t> EndIndex = positionToOffset(Contents, End, false);
llvm::Expected<size_t> EndIndex = positionToOffset(Contents, End, false);
if (!EndIndex)
return EndIndex.takeError();

if (*EndIndex < *StartIndex)
return make_error<StringError>(
formatv("Range's end position ({0}) is before start position ({1})",
End, Start),
return llvm::make_error<llvm::StringError>(
llvm::formatv(
"Range's end position ({0}) is before start position ({1})", End,
Start),
llvm::errc::invalid_argument);

// Since the range length between two LSP positions is dependent on the
Expand All @@ -88,10 +88,10 @@ DraftStore::updateDraft(PathRef File,
lspLength(Contents.substr(*StartIndex, *EndIndex - *StartIndex));

if (Change.rangeLength && ComputedRangeLength != *Change.rangeLength)
return make_error<StringError>(
formatv("Change's rangeLength ({0}) doesn't match the "
"computed range length ({1}).",
*Change.rangeLength, *EndIndex - *StartIndex),
return llvm::make_error<llvm::StringError>(
llvm::formatv("Change's rangeLength ({0}) doesn't match the "
"computed range length ({1}).",
*Change.rangeLength, *EndIndex - *StartIndex),
llvm::errc::invalid_argument);

std::string NewContents;
Expand Down
14 changes: 7 additions & 7 deletions clang-tools-extra/clangd/ExpectedTypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
#include "clang/Sema/CodeCompleteConsumer.h"
#include "llvm/ADT/STLExtras.h"

using namespace llvm;

namespace clang {
namespace clangd {
namespace {
Expand All @@ -33,7 +31,8 @@ static const Type *toEquivClass(ASTContext &Ctx, QualType T) {
return T.getTypePtr();
}

static Optional<QualType> typeOfCompletion(const CodeCompletionResult &R) {
static llvm::Optional<QualType>
typeOfCompletion(const CodeCompletionResult &R) {
auto *VD = dyn_cast_or_null<ValueDecl>(R.Declaration);
if (!VD)
return None; // We handle only variables and functions below.
Expand All @@ -49,25 +48,26 @@ static Optional<QualType> typeOfCompletion(const CodeCompletionResult &R) {
}
} // namespace

Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
llvm::Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
if (T.isNull())
return None;
const Type *C = toEquivClass(Ctx, T);
if (!C)
return None;
SmallString<128> Encoded;
llvm::SmallString<128> Encoded;
if (index::generateUSRForType(QualType(C, 0), Ctx, Encoded))
return None;
return OpaqueType(Encoded.str());
}

OpaqueType::OpaqueType(std::string Data) : Data(std::move(Data)) {}

Optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx, QualType Type) {
llvm::Optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx,
QualType Type) {
return encode(Ctx, Type);
}

Optional<OpaqueType>
llvm::Optional<OpaqueType>
OpaqueType::fromCompletionResult(ASTContext &Ctx,
const CodeCompletionResult &R) {
auto T = typeOfCompletion(R);
Expand Down
44 changes: 24 additions & 20 deletions clang-tools-extra/clangd/FS.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@
#include "llvm/ADT/None.h"
#include "llvm/Support/Path.h"

using namespace llvm;
namespace clang {
namespace clangd {

PreambleFileStatusCache::PreambleFileStatusCache(StringRef MainFilePath)
PreambleFileStatusCache::PreambleFileStatusCache(llvm::StringRef MainFilePath)
: MainFilePath(MainFilePath) {
assert(sys::path::is_absolute(MainFilePath));
assert(llvm::sys::path::is_absolute(MainFilePath));
}

void PreambleFileStatusCache::update(const vfs::FileSystem &FS, vfs::Status S) {
SmallString<32> PathStore(S.getName());
void PreambleFileStatusCache::update(const llvm::vfs::FileSystem &FS,
llvm::vfs::Status S) {
llvm::SmallString<32> PathStore(S.getName());
if (FS.makeAbsolute(PathStore))
return;
// Do not cache status for the main file.
Expand All @@ -32,25 +32,27 @@ void PreambleFileStatusCache::update(const vfs::FileSystem &FS, vfs::Status S) {
StatCache.insert({PathStore, std::move(S)});
}

Optional<vfs::Status> PreambleFileStatusCache::lookup(StringRef File) const {
llvm::Optional<llvm::vfs::Status>
PreambleFileStatusCache::lookup(llvm::StringRef File) const {
auto I = StatCache.find(File);
if (I != StatCache.end())
return I->getValue();
return None;
}

IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getProducingFS(
IntrusiveRefCntPtr<vfs::FileSystem> FS) {
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
PreambleFileStatusCache::getProducingFS(
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) {
// This invalidates old status in cache if files are re-`open()`ed or
// re-`stat()`ed in case file status has changed during preamble build.
class CollectFS : public vfs::ProxyFileSystem {
class CollectFS : public llvm::vfs::ProxyFileSystem {
public:
CollectFS(IntrusiveRefCntPtr<vfs::FileSystem> FS,
CollectFS(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
PreambleFileStatusCache &StatCache)
: ProxyFileSystem(std::move(FS)), StatCache(StatCache) {}

ErrorOr<std::unique_ptr<vfs::File>>
openFileForRead(const Twine &Path) override {
llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
openFileForRead(const llvm::Twine &Path) override {
auto File = getUnderlyingFS().openFileForRead(Path);
if (!File || !*File)
return File;
Expand All @@ -64,7 +66,7 @@ IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getProducingFS(
return File;
}

ErrorOr<vfs::Status> status(const Twine &Path) override {
llvm::ErrorOr<llvm::vfs::Status> status(const llvm::Twine &Path) override {
auto S = getUnderlyingFS().status(Path);
if (S)
StatCache.update(getUnderlyingFS(), *S);
Expand All @@ -74,18 +76,20 @@ IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getProducingFS(
private:
PreambleFileStatusCache &StatCache;
};
return IntrusiveRefCntPtr<CollectFS>(new CollectFS(std::move(FS), *this));
return llvm::IntrusiveRefCntPtr<CollectFS>(
new CollectFS(std::move(FS), *this));
}

IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getConsumingFS(
IntrusiveRefCntPtr<vfs::FileSystem> FS) const {
class CacheVFS : public vfs::ProxyFileSystem {
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
PreambleFileStatusCache::getConsumingFS(
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) const {
class CacheVFS : public llvm::vfs::ProxyFileSystem {
public:
CacheVFS(IntrusiveRefCntPtr<vfs::FileSystem> FS,
CacheVFS(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
const PreambleFileStatusCache &StatCache)
: ProxyFileSystem(std::move(FS)), StatCache(StatCache) {}

ErrorOr<vfs::Status> status(const Twine &Path) override {
llvm::ErrorOr<llvm::vfs::Status> status(const llvm::Twine &Path) override {
if (auto S = StatCache.lookup(Path.str()))
return *S;
return getUnderlyingFS().status(Path);
Expand All @@ -94,7 +98,7 @@ IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getConsumingFS(
private:
const PreambleFileStatusCache &StatCache;
};
return IntrusiveRefCntPtr<CacheVFS>(new CacheVFS(std::move(FS), *this));
return llvm::IntrusiveRefCntPtr<CacheVFS>(new CacheVFS(std::move(FS), *this));
}

} // namespace clangd
Expand Down
24 changes: 12 additions & 12 deletions clang-tools-extra/clangd/FSProvider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
#include "llvm/Support/VirtualFileSystem.h"
#include <memory>

using namespace llvm;

namespace clang {
namespace clangd {

Expand All @@ -28,38 +26,40 @@ class VolatileFileSystem : public llvm::vfs::ProxyFileSystem {
explicit VolatileFileSystem(llvm::IntrusiveRefCntPtr<FileSystem> FS)
: ProxyFileSystem(std::move(FS)) {}

llvm::ErrorOr<std::unique_ptr<vfs::File>>
openFileForRead(const Twine &InPath) override {
SmallString<128> Path;
llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
openFileForRead(const llvm::Twine &InPath) override {
llvm::SmallString<128> Path;
InPath.toVector(Path);

auto File = getUnderlyingFS().openFileForRead(Path);
if (!File)
return File;
// Try to guess preamble files, they can be memory-mapped even on Windows as
// clangd has exclusive access to those.
StringRef FileName = llvm::sys::path::filename(Path);
llvm::StringRef FileName = llvm::sys::path::filename(Path);
if (FileName.startswith("preamble-") && FileName.endswith(".pch"))
return File;
return std::unique_ptr<VolatileFile>(new VolatileFile(std::move(*File)));
}

private:
class VolatileFile : public vfs::File {
class VolatileFile : public llvm::vfs::File {
public:
VolatileFile(std::unique_ptr<vfs::File> Wrapped)
VolatileFile(std::unique_ptr<llvm::vfs::File> Wrapped)
: Wrapped(std::move(Wrapped)) {
assert(this->Wrapped);
}

virtual llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
bool /*IsVolatile*/) override {
getBuffer(const llvm::Twine &Name, int64_t FileSize,
bool RequiresNullTerminator, bool /*IsVolatile*/) override {
return Wrapped->getBuffer(Name, FileSize, RequiresNullTerminator,
/*IsVolatile=*/true);
}

llvm::ErrorOr<vfs::Status> status() override { return Wrapped->status(); }
llvm::ErrorOr<llvm::vfs::Status> status() override {
return Wrapped->status();
}
llvm::ErrorOr<std::string> getName() override { return Wrapped->getName(); }
std::error_code close() override { return Wrapped->close(); }

Expand All @@ -77,7 +77,7 @@ clang::clangd::RealFileSystemProvider::getFileSystem() const {
#ifdef _WIN32
return new VolatileFileSystem(vfs::getRealFileSystem());
#else
return vfs::getRealFileSystem();
return llvm::vfs::getRealFileSystem();
#endif
}
} // namespace clangd
Expand Down
71 changes: 37 additions & 34 deletions clang-tools-extra/clangd/FileDistance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
#include "llvm/ADT/STLExtras.h"
#include <queue>

using namespace llvm;
namespace clang {
namespace clangd {

Expand All @@ -45,35 +44,37 @@ namespace clangd {
// C:\foo\bar --> /c:/foo/bar
// /foo/ --> /foo
// a/b/c --> /a/b/c
static SmallString<128> canonicalize(StringRef Path) {
SmallString<128> Result = Path.rtrim('/');
native(Result, sys::path::Style::posix);
static llvm::SmallString<128> canonicalize(llvm::StringRef Path) {
llvm::SmallString<128> Result = Path.rtrim('/');
native(Result, llvm::sys::path::Style::posix);
if (Result.empty() || Result.front() != '/')
Result.insert(Result.begin(), '/');
return Result;
}

constexpr const unsigned FileDistance::Unreachable;
const hash_code FileDistance::RootHash = hash_value(StringRef("/"));
const llvm::hash_code FileDistance::RootHash =
llvm::hash_value(llvm::StringRef("/"));

FileDistance::FileDistance(StringMap<SourceParams> Sources,
FileDistance::FileDistance(llvm::StringMap<SourceParams> Sources,
const FileDistanceOptions &Opts)
: Opts(Opts) {
DenseMap<hash_code, SmallVector<hash_code, 4>> DownEdges;
llvm::DenseMap<llvm::hash_code, llvm::SmallVector<llvm::hash_code, 4>>
DownEdges;
// Compute the best distance following only up edges.
// Keep track of down edges, in case we can use them to improve on this.
for (const auto &S : Sources) {
auto Canonical = canonicalize(S.getKey());
dlog("Source {0} = {1}, MaxUp = {2}", Canonical, S.second.Cost,
S.second.MaxUpTraversals);
// Walk up to ancestors of this source, assigning cost.
StringRef Rest = Canonical;
hash_code Hash = hash_value(Rest);
llvm::StringRef Rest = Canonical;
llvm::hash_code Hash = llvm::hash_value(Rest);
for (unsigned I = 0; !Rest.empty(); ++I) {
Rest = parent_path(Rest, sys::path::Style::posix);
auto NextHash = hash_value(Rest);
Rest = parent_path(Rest, llvm::sys::path::Style::posix);
auto NextHash = llvm::hash_value(Rest);
auto &Down = DownEdges[NextHash];
if (!is_contained(Down, Hash))
if (!llvm::is_contained(Down, Hash))
Down.push_back(Hash);
// We can't just break after MaxUpTraversals, must still set DownEdges.
if (I > S.getValue().MaxUpTraversals) {
Expand All @@ -96,8 +97,8 @@ FileDistance::FileDistance(StringMap<SourceParams> Sources,
}
// Now propagate scores parent -> child if that's an improvement.
// BFS ensures we propagate down chains (must visit parents before children).
std::queue<hash_code> Next;
for (auto Child : DownEdges.lookup(hash_value(StringRef(""))))
std::queue<llvm::hash_code> Next;
for (auto Child : DownEdges.lookup(llvm::hash_value(llvm::StringRef(""))))
Next.push(Child);
while (!Next.empty()) {
auto Parent = Next.front();
Expand All @@ -115,14 +116,14 @@ FileDistance::FileDistance(StringMap<SourceParams> Sources,
}
}

unsigned FileDistance::distance(StringRef Path) {
unsigned FileDistance::distance(llvm::StringRef Path) {
auto Canonical = canonicalize(Path);
unsigned Cost = Unreachable;
SmallVector<hash_code, 16> Ancestors;
llvm::SmallVector<llvm::hash_code, 16> Ancestors;
// Walk up ancestors until we find a path we know the distance for.
for (StringRef Rest = Canonical; !Rest.empty();
Rest = parent_path(Rest, sys::path::Style::posix)) {
auto Hash = hash_value(Rest);
for (llvm::StringRef Rest = Canonical; !Rest.empty();
Rest = parent_path(Rest, llvm::sys::path::Style::posix)) {
auto Hash = llvm::hash_value(Rest);
if (Hash == RootHash && !Ancestors.empty() &&
!Opts.AllowDownTraversalFromRoot) {
Cost = Unreachable;
Expand All @@ -137,7 +138,7 @@ unsigned FileDistance::distance(StringRef Path) {
}
// Now we know the costs for (known node, queried node].
// Fill these in, walking down the directory tree.
for (hash_code Hash : reverse(Ancestors)) {
for (llvm::hash_code Hash : llvm::reverse(Ancestors)) {
if (Cost != Unreachable)
Cost += Opts.DownCost;
Cache.try_emplace(Hash, Cost);
Expand All @@ -146,8 +147,8 @@ unsigned FileDistance::distance(StringRef Path) {
return Cost;
}

unsigned URIDistance::distance(StringRef URI) {
auto R = Cache.try_emplace(hash_value(URI), FileDistance::Unreachable);
unsigned URIDistance::distance(llvm::StringRef URI) {
auto R = Cache.try_emplace(llvm::hash_value(URI), FileDistance::Unreachable);
if (!R.second)
return R.first->getSecond();
if (auto U = clangd::URI::parse(URI)) {
Expand All @@ -159,15 +160,15 @@ unsigned URIDistance::distance(StringRef URI) {
return R.first->second;
}

FileDistance &URIDistance::forScheme(StringRef Scheme) {
FileDistance &URIDistance::forScheme(llvm::StringRef Scheme) {
auto &Delegate = ByScheme[Scheme];
if (!Delegate) {
StringMap<SourceParams> SchemeSources;
llvm::StringMap<SourceParams> SchemeSources;
for (const auto &Source : Sources) {
if (auto U = clangd::URI::create(Source.getKey(), Scheme))
SchemeSources.try_emplace(U->body(), Source.getValue());
else
consumeError(U.takeError());
llvm::consumeError(U.takeError());
}
dlog("FileDistance for scheme {0}: {1}/{2} sources", Scheme,
SchemeSources.size(), Sources.size());
Expand All @@ -176,21 +177,23 @@ FileDistance &URIDistance::forScheme(StringRef Scheme) {
return *Delegate;
}

static std::pair<std::string, int> scopeToPath(StringRef Scope) {
SmallVector<StringRef, 4> Split;
static std::pair<std::string, int> scopeToPath(llvm::StringRef Scope) {
llvm::SmallVector<llvm::StringRef, 4> Split;
Scope.split(Split, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
return {"/" + join(Split, "/"), Split.size()};
return {"/" + llvm::join(Split, "/"), Split.size()};
}

static FileDistance createScopeFileDistance(ArrayRef<std::string> QueryScopes) {
static FileDistance
createScopeFileDistance(llvm::ArrayRef<std::string> QueryScopes) {
FileDistanceOptions Opts;
Opts.UpCost = 2;
Opts.DownCost = 4;
Opts.AllowDownTraversalFromRoot = false;

StringMap<SourceParams> Sources;
StringRef Preferred = QueryScopes.empty() ? "" : QueryScopes.front().c_str();
for (StringRef S : QueryScopes) {
llvm::StringMap<SourceParams> Sources;
llvm::StringRef Preferred =
QueryScopes.empty() ? "" : QueryScopes.front().c_str();
for (llvm::StringRef S : QueryScopes) {
SourceParams Param;
// Penalize the global scope even it's preferred, as all projects can define
// symbols in it, and there is pattern where using-namespace is used in
Expand All @@ -209,10 +212,10 @@ static FileDistance createScopeFileDistance(ArrayRef<std::string> QueryScopes) {
return FileDistance(Sources, Opts);
}

ScopeDistance::ScopeDistance(ArrayRef<std::string> QueryScopes)
ScopeDistance::ScopeDistance(llvm::ArrayRef<std::string> QueryScopes)
: Distance(createScopeFileDistance(QueryScopes)) {}

unsigned ScopeDistance::distance(StringRef SymbolScope) {
unsigned ScopeDistance::distance(llvm::StringRef SymbolScope) {
return Distance.distance(scopeToPath(SymbolScope).first);
}

Expand Down
9 changes: 4 additions & 5 deletions clang-tools-extra/clangd/FindSymbols.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

#define DEBUG_TYPE "FindSymbols"

using namespace llvm;
namespace clang {
namespace clangd {
namespace {
Expand Down Expand Up @@ -100,9 +99,9 @@ struct ScoredSymbolGreater {

} // namespace

Expected<std::vector<SymbolInformation>>
getWorkspaceSymbols(StringRef Query, int Limit, const SymbolIndex *const Index,
StringRef HintPath) {
llvm::Expected<std::vector<SymbolInformation>>
getWorkspaceSymbols(llvm::StringRef Query, int Limit,
const SymbolIndex *const Index, llvm::StringRef HintPath) {
std::vector<SymbolInformation> Result;
if (Query.empty() || !Index)
return Result;
Expand Down Expand Up @@ -153,7 +152,7 @@ getWorkspaceSymbols(StringRef Query, int Limit, const SymbolIndex *const Index,
L.range = {Start, End};
SymbolKind SK = indexSymbolKindToSymbolKind(Sym.SymInfo.Kind);
std::string Scope = Sym.Scope;
StringRef ScopeRef = Scope;
llvm::StringRef ScopeRef = Scope;
ScopeRef.consume_back("::");
SymbolInformation Info = {Sym.Name, SK, L, ScopeRef};

Expand Down
46 changes: 23 additions & 23 deletions clang-tools-extra/clangd/FuzzyMatch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@
#include "llvm/ADT/Optional.h"
#include "llvm/Support/Format.h"

using namespace llvm;
namespace clang {
namespace clangd {

Expand All @@ -75,7 +74,7 @@ static constexpr int AwfulScore = -(1 << 13);
static bool isAwful(int S) { return S < AwfulScore / 2; }
static constexpr int PerfectBonus = 3; // Perfect per-pattern-char score.

FuzzyMatcher::FuzzyMatcher(StringRef Pattern)
FuzzyMatcher::FuzzyMatcher(llvm::StringRef Pattern)
: PatN(std::min<int>(MaxPat, Pattern.size())),
ScoreScale(PatN ? float{1} / (PerfectBonus * PatN) : 0), WordN(0) {
std::copy(Pattern.begin(), Pattern.begin() + PatN, Pat);
Expand All @@ -87,20 +86,20 @@ FuzzyMatcher::FuzzyMatcher(StringRef Pattern)
for (int W = 0; W < P; ++W)
for (Action A : {Miss, Match})
Scores[P][W][A] = {AwfulScore, Miss};
PatTypeSet =
calculateRoles(StringRef(Pat, PatN), makeMutableArrayRef(PatRole, PatN));
PatTypeSet = calculateRoles(llvm::StringRef(Pat, PatN),
llvm::makeMutableArrayRef(PatRole, PatN));
}

Optional<float> FuzzyMatcher::match(StringRef Word) {
llvm::Optional<float> FuzzyMatcher::match(llvm::StringRef Word) {
if (!(WordContainsPattern = init(Word)))
return None;
return llvm::None;
if (!PatN)
return 1;
buildGraph();
auto Best = std::max(Scores[PatN][WordN][Miss].Score,
Scores[PatN][WordN][Match].Score);
if (isAwful(Best))
return None;
return llvm::None;
float Score =
ScoreScale * std::min(PerfectBonus * PatN, std::max<int>(0, Best));
// If the pattern is as long as the word, we have an exact string match,
Expand Down Expand Up @@ -153,7 +152,8 @@ constexpr static uint8_t CharRoles[] = {
template <typename T> static T packedLookup(const uint8_t *Data, int I) {
return static_cast<T>((Data[I >> 2] >> ((I & 3) * 2)) & 3);
}
CharTypeSet calculateRoles(StringRef Text, MutableArrayRef<CharRole> Roles) {
CharTypeSet calculateRoles(llvm::StringRef Text,
llvm::MutableArrayRef<CharRole> Roles) {
assert(Text.size() == Roles.size());
if (Text.size() == 0)
return 0;
Expand All @@ -179,7 +179,7 @@ CharTypeSet calculateRoles(StringRef Text, MutableArrayRef<CharRole> Roles) {

// Sets up the data structures matching Word.
// Returns false if we can cheaply determine that no match is possible.
bool FuzzyMatcher::init(StringRef NewWord) {
bool FuzzyMatcher::init(llvm::StringRef NewWord) {
WordN = std::min<int>(MaxWord, NewWord.size());
if (PatN > WordN)
return false;
Expand All @@ -200,8 +200,8 @@ bool FuzzyMatcher::init(StringRef NewWord) {
// FIXME: some words are hard to tokenize algorithmically.
// e.g. vsprintf is V S Print F, and should match [pri] but not [int].
// We could add a tokenization dictionary for common stdlib names.
WordTypeSet = calculateRoles(StringRef(Word, WordN),
makeMutableArrayRef(WordRole, WordN));
WordTypeSet = calculateRoles(llvm::StringRef(Word, WordN),
llvm::makeMutableArrayRef(WordRole, WordN));
return true;
}

Expand Down Expand Up @@ -299,13 +299,13 @@ int FuzzyMatcher::matchBonus(int P, int W, Action Last) const {
return S;
}

SmallString<256> FuzzyMatcher::dumpLast(raw_ostream &OS) const {
SmallString<256> Result;
OS << "=== Match \"" << StringRef(Word, WordN) << "\" against ["
<< StringRef(Pat, PatN) << "] ===\n";
llvm::SmallString<256> FuzzyMatcher::dumpLast(llvm::raw_ostream &OS) const {
llvm::SmallString<256> Result;
OS << "=== Match \"" << llvm::StringRef(Word, WordN) << "\" against ["
<< llvm::StringRef(Pat, PatN) << "] ===\n";
if (PatN == 0) {
OS << "Pattern is empty: perfect match.\n";
return Result = StringRef(Word, WordN);
return Result = llvm::StringRef(Word, WordN);
}
if (WordN == 0) {
OS << "Word is empty: no match.\n";
Expand Down Expand Up @@ -349,28 +349,28 @@ SmallString<256> FuzzyMatcher::dumpLast(raw_ostream &OS) const {
if (A[WordN - 1] == Match)
Result.push_back(']');

for (char C : StringRef(Word, WordN))
for (char C : llvm::StringRef(Word, WordN))
OS << " " << C << " ";
OS << "\n";
for (int I = 0, J = 0; I < WordN; I++)
OS << " " << (A[I] == Match ? Pat[J++] : ' ') << " ";
OS << "\n";
for (int I = 0; I < WordN; I++)
OS << format("%2d ", S[I]);
OS << llvm::format("%2d ", S[I]);
OS << "\n";

OS << "\nSegmentation:";
OS << "\n'" << StringRef(Word, WordN) << "'\n ";
OS << "\n'" << llvm::StringRef(Word, WordN) << "'\n ";
for (int I = 0; I < WordN; ++I)
OS << "?-+ "[static_cast<int>(WordRole[I])];
OS << "\n[" << StringRef(Pat, PatN) << "]\n ";
OS << "\n[" << llvm::StringRef(Pat, PatN) << "]\n ";
for (int I = 0; I < PatN; ++I)
OS << "?-+ "[static_cast<int>(PatRole[I])];
OS << "\n";

OS << "\nScoring table (last-Miss, last-Match):\n";
OS << " | ";
for (char C : StringRef(Word, WordN))
for (char C : llvm::StringRef(Word, WordN))
OS << " " << C << " ";
OS << "\n";
OS << "-+----" << std::string(WordN * 4, '-') << "\n";
Expand All @@ -379,8 +379,8 @@ SmallString<256> FuzzyMatcher::dumpLast(raw_ostream &OS) const {
OS << ((I && A == Miss) ? Pat[I - 1] : ' ') << "|";
for (int J = 0; J <= WordN; ++J) {
if (!isAwful(Scores[I][J][A].Score))
OS << format("%3d%c", Scores[I][J][A].Score,
Scores[I][J][A].Prev == Match ? '*' : ' ');
OS << llvm::format("%3d%c", Scores[I][J][A].Score,
Scores[I][J][A].Prev == Match ? '*' : ' ');
else
OS << " ";
}
Expand Down
17 changes: 9 additions & 8 deletions clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"

using namespace llvm;
namespace clang {
namespace clangd {

Expand All @@ -32,22 +31,24 @@ GlobalCompilationDatabase::getFallbackCommand(PathRef File) const {
std::vector<std::string> Argv = {getFallbackClangPath()};
// Clang treats .h files as C by default, resulting in unhelpful diagnostics.
// Parsing as Objective C++ is friendly to more cases.
if (sys::path::extension(File) == ".h")
if (llvm::sys::path::extension(File) == ".h")
Argv.push_back("-xobjective-c++-header");
Argv.push_back(File);
return tooling::CompileCommand(sys::path::parent_path(File),
sys::path::filename(File), std::move(Argv),
return tooling::CompileCommand(llvm::sys::path::parent_path(File),
llvm::sys::path::filename(File),
std::move(Argv),
/*Output=*/"");
}

DirectoryBasedGlobalCompilationDatabase::
DirectoryBasedGlobalCompilationDatabase(Optional<Path> CompileCommandsDir)
DirectoryBasedGlobalCompilationDatabase(
llvm::Optional<Path> CompileCommandsDir)
: CompileCommandsDir(std::move(CompileCommandsDir)) {}

DirectoryBasedGlobalCompilationDatabase::
~DirectoryBasedGlobalCompilationDatabase() = default;

Optional<tooling::CompileCommand>
llvm::Optional<tooling::CompileCommand>
DirectoryBasedGlobalCompilationDatabase::getCompileCommand(
PathRef File, ProjectInfo *Project) const {
if (auto CDB = getCDBForFile(File, Project)) {
Expand Down Expand Up @@ -77,7 +78,7 @@ DirectoryBasedGlobalCompilationDatabase::getCDBInDirLocked(PathRef Dir) const {
tooling::CompilationDatabase *
DirectoryBasedGlobalCompilationDatabase::getCDBForFile(
PathRef File, ProjectInfo *Project) const {
namespace path = sys::path;
namespace path = llvm::sys::path;
assert((path::is_absolute(File, path::Style::posix) ||
path::is_absolute(File, path::Style::windows)) &&
"path must be absolute");
Expand Down Expand Up @@ -113,7 +114,7 @@ OverlayCDB::OverlayCDB(const GlobalCompilationDatabase *Base,
});
}

Optional<tooling::CompileCommand>
llvm::Optional<tooling::CompileCommand>
OverlayCDB::getCompileCommand(PathRef File, ProjectInfo *Project) const {
{
std::lock_guard<std::mutex> Lock(Mutex);
Expand Down
32 changes: 17 additions & 15 deletions clang-tools-extra/clangd/Headers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
#include "clang/Lex/HeaderSearch.h"
#include "llvm/Support/Path.h"

using namespace llvm;
namespace clang {
namespace clangd {
namespace {
Expand All @@ -30,9 +29,10 @@ class RecordHeaders : public PPCallbacks {
// Record existing #includes - both written and resolved paths. Only #includes
// in the main file are collected.
void InclusionDirective(SourceLocation HashLoc, const Token & /*IncludeTok*/,
StringRef FileName, bool IsAngled,
llvm::StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange, const FileEntry *File,
StringRef /*SearchPath*/, StringRef /*RelativePath*/,
llvm::StringRef /*SearchPath*/,
llvm::StringRef /*RelativePath*/,
const Module * /*Imported*/,
SrcMgr::CharacteristicKind FileKind) override {
if (SM.isWrittenInMainFile(HashLoc)) {
Expand Down Expand Up @@ -65,13 +65,13 @@ class RecordHeaders : public PPCallbacks {

} // namespace

bool isLiteralInclude(StringRef Include) {
bool isLiteralInclude(llvm::StringRef Include) {
return Include.startswith("<") || Include.startswith("\"");
}

bool HeaderFile::valid() const {
return (Verbatim && isLiteralInclude(File)) ||
(!Verbatim && sys::path::is_absolute(File));
(!Verbatim && llvm::sys::path::is_absolute(File));
}

std::unique_ptr<PPCallbacks>
Expand All @@ -80,29 +80,30 @@ collectIncludeStructureCallback(const SourceManager &SM,
return llvm::make_unique<RecordHeaders>(SM, Out);
}

void IncludeStructure::recordInclude(StringRef IncludingName,
StringRef IncludedName,
StringRef IncludedRealName) {
void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
llvm::StringRef IncludedName,
llvm::StringRef IncludedRealName) {
auto Child = fileIndex(IncludedName);
if (!IncludedRealName.empty() && RealPathNames[Child].empty())
RealPathNames[Child] = IncludedRealName;
auto Parent = fileIndex(IncludingName);
IncludeChildren[Parent].push_back(Child);
}

unsigned IncludeStructure::fileIndex(StringRef Name) {
unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
if (R.second)
RealPathNames.emplace_back();
return R.first->getValue();
}

StringMap<unsigned> IncludeStructure::includeDepth(StringRef Root) const {
llvm::StringMap<unsigned>
IncludeStructure::includeDepth(llvm::StringRef Root) const {
// Include depth 0 is the main file only.
StringMap<unsigned> Result;
llvm::StringMap<unsigned> Result;
Result[Root] = 0;
std::vector<unsigned> CurrentLevel;
DenseSet<unsigned> Seen;
llvm::DenseSet<unsigned> Seen;
auto It = NameToIndex.find(Root);
if (It != NameToIndex.end()) {
CurrentLevel.push_back(It->second);
Expand Down Expand Up @@ -142,7 +143,7 @@ bool IncludeInserter::shouldInsertInclude(
assert(DeclaringHeader.valid() && InsertedHeader.valid());
if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
return false;
auto Included = [&](StringRef Header) {
auto Included = [&](llvm::StringRef Header) {
return IncludedHeaders.find(Header) != IncludedHeaders.end();
};
return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
Expand All @@ -164,8 +165,9 @@ IncludeInserter::calculateIncludePath(const HeaderFile &DeclaringHeader,
return Suggested;
}

Optional<TextEdit> IncludeInserter::insert(StringRef VerbatimHeader) const {
Optional<TextEdit> Edit = None;
llvm::Optional<TextEdit>
IncludeInserter::insert(llvm::StringRef VerbatimHeader) const {
llvm::Optional<TextEdit> Edit = None;
if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
VerbatimHeader.startswith("<")))
Edit = replacementToEdit(Code, *Insertion);
Expand Down
118 changes: 62 additions & 56 deletions clang-tools-extra/clangd/JSONTransport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,131 +11,135 @@
#include "Transport.h"
#include "llvm/Support/Errno.h"

using namespace llvm;
namespace clang {
namespace clangd {
namespace {

json::Object encodeError(Error E) {
llvm::json::Object encodeError(llvm::Error E) {
std::string Message;
ErrorCode Code = ErrorCode::UnknownErrorCode;
if (Error Unhandled =
handleErrors(std::move(E), [&](const LSPError &L) -> Error {
if (llvm::Error Unhandled = llvm::handleErrors(
std::move(E), [&](const LSPError &L) -> llvm::Error {
Message = L.Message;
Code = L.Code;
return Error::success();
return llvm::Error::success();
}))
Message = toString(std::move(Unhandled));
Message = llvm::toString(std::move(Unhandled));

return json::Object{
return llvm::json::Object{
{"message", std::move(Message)},
{"code", int64_t(Code)},
};
}

Error decodeError(const json::Object &O) {
llvm::Error decodeError(const llvm::json::Object &O) {
std::string Msg = O.getString("message").getValueOr("Unspecified error");
if (auto Code = O.getInteger("code"))
return make_error<LSPError>(std::move(Msg), ErrorCode(*Code));
return make_error<StringError>(std::move(Msg), inconvertibleErrorCode());
return llvm::make_error<LSPError>(std::move(Msg), ErrorCode(*Code));
return llvm::make_error<llvm::StringError>(std::move(Msg),
llvm::inconvertibleErrorCode());
}

class JSONTransport : public Transport {
public:
JSONTransport(std::FILE *In, raw_ostream &Out, raw_ostream *InMirror,
bool Pretty, JSONStreamStyle Style)
: In(In), Out(Out), InMirror(InMirror ? *InMirror : nulls()),
JSONTransport(std::FILE *In, llvm::raw_ostream &Out,
llvm::raw_ostream *InMirror, bool Pretty, JSONStreamStyle Style)
: In(In), Out(Out), InMirror(InMirror ? *InMirror : llvm::nulls()),
Pretty(Pretty), Style(Style) {}

void notify(StringRef Method, json::Value Params) override {
sendMessage(json::Object{
void notify(llvm::StringRef Method, llvm::json::Value Params) override {
sendMessage(llvm::json::Object{
{"jsonrpc", "2.0"},
{"method", Method},
{"params", std::move(Params)},
});
}
void call(StringRef Method, json::Value Params, json::Value ID) override {
sendMessage(json::Object{
void call(llvm::StringRef Method, llvm::json::Value Params,
llvm::json::Value ID) override {
sendMessage(llvm::json::Object{
{"jsonrpc", "2.0"},
{"id", std::move(ID)},
{"method", Method},
{"params", std::move(Params)},
});
}
void reply(json::Value ID, Expected<json::Value> Result) override {
void reply(llvm::json::Value ID,
llvm::Expected<llvm::json::Value> Result) override {
if (Result) {
sendMessage(json::Object{
sendMessage(llvm::json::Object{
{"jsonrpc", "2.0"},
{"id", std::move(ID)},
{"result", std::move(*Result)},
});
} else {
sendMessage(json::Object{
sendMessage(llvm::json::Object{
{"jsonrpc", "2.0"},
{"id", std::move(ID)},
{"error", encodeError(Result.takeError())},
});
}
}

Error loop(MessageHandler &Handler) override {
llvm::Error loop(MessageHandler &Handler) override {
while (!feof(In)) {
if (ferror(In))
return errorCodeToError(std::error_code(errno, std::system_category()));
return llvm::errorCodeToError(
std::error_code(errno, std::system_category()));
if (auto JSON = readRawMessage()) {
if (auto Doc = json::parse(*JSON)) {
if (auto Doc = llvm::json::parse(*JSON)) {
vlog(Pretty ? "<<< {0:2}\n" : "<<< {0}\n", *Doc);
if (!handleMessage(std::move(*Doc), Handler))
return Error::success(); // we saw the "exit" notification.
return llvm::Error::success(); // we saw the "exit" notification.
} else {
// Parse error. Log the raw message.
vlog("<<< {0}\n", *JSON);
elog("JSON parse error: {0}", toString(Doc.takeError()));
elog("JSON parse error: {0}", llvm::toString(Doc.takeError()));
}
}
}
return errorCodeToError(std::make_error_code(std::errc::io_error));
return llvm::errorCodeToError(std::make_error_code(std::errc::io_error));
}

private:
// Dispatches incoming message to Handler onNotify/onCall/onReply.
bool handleMessage(json::Value Message, MessageHandler &Handler);
bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
// Writes outgoing message to Out stream.
void sendMessage(json::Value Message) {
void sendMessage(llvm::json::Value Message) {
std::string S;
raw_string_ostream OS(S);
OS << formatv(Pretty ? "{0:2}" : "{0}", Message);
llvm::raw_string_ostream OS(S);
OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
OS.flush();
Out << "Content-Length: " << S.size() << "\r\n\r\n" << S;
Out.flush();
vlog(">>> {0}\n", S);
}

// Read raw string messages from input stream.
Optional<std::string> readRawMessage() {
llvm::Optional<std::string> readRawMessage() {
return Style == JSONStreamStyle::Delimited ? readDelimitedMessage()
: readStandardMessage();
}
Optional<std::string> readDelimitedMessage();
Optional<std::string> readStandardMessage();
llvm::Optional<std::string> readDelimitedMessage();
llvm::Optional<std::string> readStandardMessage();

std::FILE *In;
raw_ostream &Out;
raw_ostream &InMirror;
llvm::raw_ostream &Out;
llvm::raw_ostream &InMirror;
bool Pretty;
JSONStreamStyle Style;
};

bool JSONTransport::handleMessage(json::Value Message,
bool JSONTransport::handleMessage(llvm::json::Value Message,
MessageHandler &Handler) {
// Message must be an object with "jsonrpc":"2.0".
auto *Object = Message.getAsObject();
if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0")) {
if (!Object ||
Object->getString("jsonrpc") != llvm::Optional<llvm::StringRef>("2.0")) {
elog("Not a JSON-RPC 2.0 message: {0:2}", Message);
return false;
}
// ID may be any JSON value. If absent, this is a notification.
Optional<json::Value> ID;
llvm::Optional<llvm::json::Value> ID;
if (auto *I = Object->get("id"))
ID = std::move(*I);
auto Method = Object->getString("method");
Expand All @@ -147,13 +151,13 @@ bool JSONTransport::handleMessage(json::Value Message,
if (auto *Err = Object->getObject("error"))
return Handler.onReply(std::move(*ID), decodeError(*Err));
// Result should be given, use null if not.
json::Value Result = nullptr;
llvm::json::Value Result = nullptr;
if (auto *R = Object->get("result"))
Result = std::move(*R);
return Handler.onReply(std::move(*ID), std::move(Result));
}
// Params should be given, use null if not.
json::Value Params = nullptr;
llvm::json::Value Params = nullptr;
if (auto *P = Object->get("params"))
Params = std::move(*P);

Expand All @@ -172,7 +176,7 @@ bool readLine(std::FILE *In, std::string &Out) {
for (;;) {
Out.resize(Size + BufSize);
// Handle EINTR which is sent when a debugger attaches on some platforms.
if (!sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
if (!llvm::sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
return false;
clearerr(In);
// If the line contained null bytes, anything after it (including \n) will
Expand All @@ -189,17 +193,17 @@ bool readLine(std::FILE *In, std::string &Out) {
// Returns None when:
// - ferror() or feof() are set.
// - Content-Length is missing or empty (protocol error)
Optional<std::string> JSONTransport::readStandardMessage() {
llvm::Optional<std::string> JSONTransport::readStandardMessage() {
// A Language Server Protocol message starts with a set of HTTP headers,
// delimited by \r\n, and terminated by an empty line (\r\n).
unsigned long long ContentLength = 0;
std::string Line;
while (true) {
if (feof(In) || ferror(In) || !readLine(In, Line))
return None;
return llvm::None;
InMirror << Line;

StringRef LineRef(Line);
llvm::StringRef LineRef(Line);

// We allow comments in headers. Technically this isn't part

Expand All @@ -214,7 +218,7 @@ Optional<std::string> JSONTransport::readStandardMessage() {
"The previous value for this message ({0}) was ignored.",
ContentLength);
}
getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
continue;
} else if (!LineRef.trim().empty()) {
// It's another header, ignore it.
Expand All @@ -231,24 +235,24 @@ Optional<std::string> JSONTransport::readStandardMessage() {
elog("Refusing to read message with long Content-Length: {0}. "
"Expect protocol errors",
ContentLength);
return None;
return llvm::None;
}
if (ContentLength == 0) {
log("Warning: Missing Content-Length header, or zero-length message.");
return None;
return llvm::None;
}

std::string JSON(ContentLength, '\0');
for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
// Handle EINTR which is sent when a debugger attaches on some platforms.
Read = sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
ContentLength - Pos, In);
Read = llvm::sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
ContentLength - Pos, In);
if (Read == 0) {
elog("Input was aborted. Read only {0} bytes of expected {1}.", Pos,
ContentLength);
return None;
return llvm::None;
}
InMirror << StringRef(&JSON[Pos], Read);
InMirror << llvm::StringRef(&JSON[Pos], Read);
clearerr(In); // If we're done, the error was transient. If we're not done,
// either it was transient or we'll see it again on retry.
Pos += Read;
Expand All @@ -261,12 +265,12 @@ Optional<std::string> JSONTransport::readStandardMessage() {
// - lines starting with # are ignored.
// This is a testing path, so favor simplicity over performance here.
// When returning None, feof() or ferror() will be set.
Optional<std::string> JSONTransport::readDelimitedMessage() {
llvm::Optional<std::string> JSONTransport::readDelimitedMessage() {
std::string JSON;
std::string Line;
while (readLine(In, Line)) {
InMirror << Line;
auto LineRef = StringRef(Line).trim();
auto LineRef = llvm::StringRef(Line).trim();
if (LineRef.startswith("#")) // comment
continue;

Expand All @@ -279,15 +283,17 @@ Optional<std::string> JSONTransport::readDelimitedMessage() {

if (ferror(In)) {
elog("Input error while reading message!");
return None;
return llvm::None;
}
return std::move(JSON); // Including at EOF
}

} // namespace

std::unique_ptr<Transport> newJSONTransport(std::FILE *In, raw_ostream &Out,
raw_ostream *InMirror, bool Pretty,
std::unique_ptr<Transport> newJSONTransport(std::FILE *In,
llvm::raw_ostream &Out,
llvm::raw_ostream *InMirror,
bool Pretty,
JSONStreamStyle Style) {
return llvm::make_unique<JSONTransport>(In, Out, InMirror, Pretty, Style);
}
Expand Down
14 changes: 7 additions & 7 deletions clang-tools-extra/clangd/Logger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
#include "llvm/Support/raw_ostream.h"
#include <mutex>

using namespace llvm;
namespace clang {
namespace clangd {

Expand All @@ -29,13 +28,14 @@ LoggingSession::LoggingSession(clangd::Logger &Instance) {

LoggingSession::~LoggingSession() { L = nullptr; }

void detail::log(Logger::Level Level, const formatv_object_base &Message) {
void detail::log(Logger::Level Level,
const llvm::formatv_object_base &Message) {
if (L)
L->log(Level, Message);
else {
static std::mutex Mu;
std::lock_guard<std::mutex> Guard(Mu);
errs() << Message << "\n";
llvm::errs() << Message << "\n";
}
}

Expand All @@ -48,14 +48,14 @@ const char *detail::debugType(const char *Filename) {
}

void StreamLogger::log(Logger::Level Level,
const formatv_object_base &Message) {
const llvm::formatv_object_base &Message) {
if (Level < MinLevel)
return;
sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
llvm::sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
trace::log(Message);
std::lock_guard<std::mutex> Guard(StreamMutex);
Logs << formatv("{0}[{1:%H:%M:%S.%L}] {2}\n", indicator(Level), Timestamp,
Message);
Logs << llvm::formatv("{0}[{1:%H:%M:%S.%L}] {2}\n", indicator(Level),
Timestamp, Message);
Logs.flush();
}

Expand Down
309 changes: 159 additions & 150 deletions clang-tools-extra/clangd/Protocol.cpp

Large diffs are not rendered by default.

88 changes: 45 additions & 43 deletions clang-tools-extra/clangd/Quality.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,9 @@
#include <algorithm>
#include <cmath>

using namespace llvm;
namespace clang {
namespace clangd {
static bool isReserved(StringRef Name) {
static bool isReserved(llvm::StringRef Name) {
// FIXME: Should we exclude _Bool and others recognized by the standard?
return Name.size() >= 2 && Name[0] == '_' &&
(isUppercase(Name[1]) || Name[1] == '_');
Expand Down Expand Up @@ -249,12 +248,13 @@ float SymbolQualitySignals::evaluate() const {
return Score;
}

raw_ostream &operator<<(raw_ostream &OS, const SymbolQualitySignals &S) {
OS << formatv("=== Symbol quality: {0}\n", S.evaluate());
OS << formatv("\tReferences: {0}\n", S.References);
OS << formatv("\tDeprecated: {0}\n", S.Deprecated);
OS << formatv("\tReserved name: {0}\n", S.ReservedName);
OS << formatv("\tCategory: {0}\n", static_cast<int>(S.Category));
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
const SymbolQualitySignals &S) {
OS << llvm::formatv("=== Symbol quality: {0}\n", S.evaluate());
OS << llvm::formatv("\tReferences: {0}\n", S.References);
OS << llvm::formatv("\tDeprecated: {0}\n", S.Deprecated);
OS << llvm::formatv("\tReserved name: {0}\n", S.ReservedName);
OS << llvm::formatv("\tCategory: {0}\n", static_cast<int>(S.Category));
return OS;
}

Expand Down Expand Up @@ -317,7 +317,7 @@ void SymbolRelevanceSignals::merge(const CodeCompletionResult &SemaCCResult) {
NeedsFixIts = !SemaCCResult.FixIts.empty();
}

static std::pair<float, unsigned> uriProximity(StringRef SymbolURI,
static std::pair<float, unsigned> uriProximity(llvm::StringRef SymbolURI,
URIDistance *D) {
if (!D || SymbolURI.empty())
return {0.f, 0u};
Expand All @@ -327,7 +327,7 @@ static std::pair<float, unsigned> uriProximity(StringRef SymbolURI,
}

static float scopeBoost(ScopeDistance &Distance,
Optional<StringRef> SymbolScope) {
llvm::Optional<llvm::StringRef> SymbolScope) {
if (!SymbolScope)
return 1;
auto D = Distance.distance(*SymbolScope);
Expand Down Expand Up @@ -397,33 +397,34 @@ float SymbolRelevanceSignals::evaluate() const {
return Score;
}

raw_ostream &operator<<(raw_ostream &OS, const SymbolRelevanceSignals &S) {
OS << formatv("=== Symbol relevance: {0}\n", S.evaluate());
OS << formatv("\tName match: {0}\n", S.NameMatch);
OS << formatv("\tForbidden: {0}\n", S.Forbidden);
OS << formatv("\tNeedsFixIts: {0}\n", S.NeedsFixIts);
OS << formatv("\tIsInstanceMember: {0}\n", S.IsInstanceMember);
OS << formatv("\tContext: {0}\n", getCompletionKindString(S.Context));
OS << formatv("\tQuery type: {0}\n", static_cast<int>(S.Query));
OS << formatv("\tScope: {0}\n", static_cast<int>(S.Scope));

OS << formatv("\tSymbol URI: {0}\n", S.SymbolURI);
OS << formatv("\tSymbol scope: {0}\n",
S.SymbolScope ? *S.SymbolScope : "<None>");
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
const SymbolRelevanceSignals &S) {
OS << llvm::formatv("=== Symbol relevance: {0}\n", S.evaluate());
OS << llvm::formatv("\tName match: {0}\n", S.NameMatch);
OS << llvm::formatv("\tForbidden: {0}\n", S.Forbidden);
OS << llvm::formatv("\tNeedsFixIts: {0}\n", S.NeedsFixIts);
OS << llvm::formatv("\tIsInstanceMember: {0}\n", S.IsInstanceMember);
OS << llvm::formatv("\tContext: {0}\n", getCompletionKindString(S.Context));
OS << llvm::formatv("\tQuery type: {0}\n", static_cast<int>(S.Query));
OS << llvm::formatv("\tScope: {0}\n", static_cast<int>(S.Scope));

OS << llvm::formatv("\tSymbol URI: {0}\n", S.SymbolURI);
OS << llvm::formatv("\tSymbol scope: {0}\n",
S.SymbolScope ? *S.SymbolScope : "<None>");

if (S.FileProximityMatch) {
auto Score = uriProximity(S.SymbolURI, S.FileProximityMatch);
OS << formatv("\tIndex URI proximity: {0} (distance={1})\n", Score.first,
Score.second);
OS << llvm::formatv("\tIndex URI proximity: {0} (distance={1})\n",
Score.first, Score.second);
}
OS << formatv("\tSema file proximity: {0}\n", S.SemaFileProximityScore);
OS << llvm::formatv("\tSema file proximity: {0}\n", S.SemaFileProximityScore);

OS << formatv("\tSema says in scope: {0}\n", S.SemaSaysInScope);
OS << llvm::formatv("\tSema says in scope: {0}\n", S.SemaSaysInScope);
if (S.ScopeProximityMatch)
OS << formatv("\tIndex scope boost: {0}\n",
scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));
OS << llvm::formatv("\tIndex scope boost: {0}\n",
scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));

OS << formatv(
OS << llvm::formatv(
"\tType matched preferred: {0} (Context type: {1}, Symbol type: {2}\n",
S.TypeMatchesPreferred, S.HadContextType, S.HadSymbolType);

Expand All @@ -441,33 +442,34 @@ static uint32_t encodeFloat(float F) {
constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);

// Get the bits of the float. Endianness is the same as for integers.
uint32_t U = FloatToBits(F);
uint32_t U = llvm::FloatToBits(F);
// IEEE 754 floats compare like sign-magnitude integers.
if (U & TopBit) // Negative float.
return 0 - U; // Map onto the low half of integers, order reversed.
return U + TopBit; // Positive floats map onto the high half of integers.
}

std::string sortText(float Score, StringRef Name) {
std::string sortText(float Score, llvm::StringRef Name) {
// We convert -Score to an integer, and hex-encode for readability.
// Example: [0.5, "foo"] -> "41000000foo"
std::string S;
raw_string_ostream OS(S);
write_hex(OS, encodeFloat(-Score), HexPrintStyle::Lower,
/*Width=*/2 * sizeof(Score));
llvm::raw_string_ostream OS(S);
llvm::write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower,
/*Width=*/2 * sizeof(Score));
OS << Name;
OS.flush();
return S;
}

raw_ostream &operator<<(raw_ostream &OS, const SignatureQualitySignals &S) {
OS << formatv("=== Signature Quality:\n");
OS << formatv("\tNumber of parameters: {0}\n", S.NumberOfParameters);
OS << formatv("\tNumber of optional parameters: {0}\n",
S.NumberOfOptionalParameters);
OS << formatv("\tContains active parameter: {0}\n",
S.ContainsActiveParameter);
OS << formatv("\tKind: {0}\n", S.Kind);
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
const SignatureQualitySignals &S) {
OS << llvm::formatv("=== Signature Quality:\n");
OS << llvm::formatv("\tNumber of parameters: {0}\n", S.NumberOfParameters);
OS << llvm::formatv("\tNumber of optional parameters: {0}\n",
S.NumberOfOptionalParameters);
OS << llvm::formatv("\tContains active parameter: {0}\n",
S.ContainsActiveParameter);
OS << llvm::formatv("\tKind: {0}\n", S.Kind);
return OS;
}

Expand Down
21 changes: 10 additions & 11 deletions clang-tools-extra/clangd/RIFF.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,21 @@
#include "RIFF.h"
#include "llvm/Support/Endian.h"

using namespace llvm;
namespace clang {
namespace clangd {
namespace riff {

static Error makeError(const char *Msg) {
return createStringError(inconvertibleErrorCode(), Msg);
static llvm::Error makeError(const char *Msg) {
return llvm::createStringError(llvm::inconvertibleErrorCode(), Msg);
}

Expected<Chunk> readChunk(StringRef &Stream) {
llvm::Expected<Chunk> readChunk(llvm::StringRef &Stream) {
if (Stream.size() < 8)
return makeError("incomplete chunk header");
Chunk C;
std::copy(Stream.begin(), Stream.begin() + 4, C.ID.begin());
Stream = Stream.drop_front(4);
uint32_t Len = support::endian::read32le(Stream.take_front(4).begin());
uint32_t Len = llvm::support::endian::read32le(Stream.take_front(4).begin());
Stream = Stream.drop_front(4);
if (Stream.size() < Len)
return makeError("truncated chunk");
Expand All @@ -39,18 +38,18 @@ Expected<Chunk> readChunk(StringRef &Stream) {
return std::move(C);
}

raw_ostream &operator<<(raw_ostream &OS, const Chunk &C) {
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Chunk &C) {
OS.write(C.ID.data(), C.ID.size());
char Size[4];
support::endian::write32le(Size, C.Data.size());
llvm::support::endian::write32le(Size, C.Data.size());
OS.write(Size, sizeof(Size));
OS << C.Data;
if (C.Data.size() % 2)
OS.write(0);
return OS;
}

Expected<File> readFile(StringRef Stream) {
llvm::Expected<File> readFile(llvm::StringRef Stream) {
auto RIFF = readChunk(Stream);
if (!RIFF)
return RIFF.takeError();
Expand All @@ -60,22 +59,22 @@ Expected<File> readFile(StringRef Stream) {
return makeError("RIFF chunk too short");
File F;
std::copy(RIFF->Data.begin(), RIFF->Data.begin() + 4, F.Type.begin());
for (StringRef Body = RIFF->Data.drop_front(4); !Body.empty();)
for (llvm::StringRef Body = RIFF->Data.drop_front(4); !Body.empty();)
if (auto Chunk = readChunk(Body)) {
F.Chunks.push_back(*Chunk);
} else
return Chunk.takeError();
return std::move(F);
}

raw_ostream &operator<<(raw_ostream &OS, const File &F) {
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const File &F) {
// To avoid copies, we serialize the outer RIFF chunk "by hand".
size_t DataLen = 4; // Predict length of RIFF chunk data.
for (const auto &C : F.Chunks)
DataLen += 4 + 4 + C.Data.size() + (C.Data.size() % 2);
OS << "RIFF";
char Size[4];
support::endian::write32le(Size, DataLen);
llvm::support::endian::write32le(Size, DataLen);
OS.write(Size, sizeof(Size));
OS.write(F.Type.data(), F.Type.size());
for (const auto &C : F.Chunks)
Expand Down
92 changes: 47 additions & 45 deletions clang-tools-extra/clangd/SourceCode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
#include "llvm/Support/Error.h"
#include "llvm/Support/Path.h"

using namespace llvm;
namespace clang {
namespace clangd {

Expand All @@ -27,7 +26,7 @@ namespace clangd {
// invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true.
// Returns true if CB returned true, false if we hit the end of string.
template <typename Callback>
static bool iterateCodepoints(StringRef U8, const Callback &CB) {
static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
for (size_t I = 0; I < U8.size();) {
unsigned char C = static_cast<unsigned char>(U8[I]);
if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
Expand All @@ -37,7 +36,7 @@ static bool iterateCodepoints(StringRef U8, const Callback &CB) {
continue;
}
// This convenient property of UTF-8 holds for all non-ASCII characters.
size_t UTF8Length = countLeadingOnes(C);
size_t UTF8Length = llvm::countLeadingOnes(C);
// 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here.
// 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug.
assert((UTF8Length >= 2 && UTF8Length <= 4) &&
Expand All @@ -54,7 +53,7 @@ static bool iterateCodepoints(StringRef U8, const Callback &CB) {
// Returns the offset into the string that matches \p Units UTF-16 code units.
// Conceptually, this converts to UTF-16, truncates to CodeUnits, converts back
// to UTF-8, and returns the length in bytes.
static size_t measureUTF16(StringRef U8, int U16Units, bool &Valid) {
static size_t measureUTF16(llvm::StringRef U8, int U16Units, bool &Valid) {
size_t Result = 0;
Valid = U16Units == 0 || iterateCodepoints(U8, [&](int U8Len, int U16Len) {
Result += U8Len;
Expand All @@ -68,7 +67,7 @@ static size_t measureUTF16(StringRef U8, int U16Units, bool &Valid) {
}

// Like most strings in clangd, the input is UTF-8 encoded.
size_t lspLength(StringRef Code) {
size_t lspLength(llvm::StringRef Code) {
// A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
// Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx.
size_t Count = 0;
Expand All @@ -79,47 +78,47 @@ size_t lspLength(StringRef Code) {
return Count;
}

Expected<size_t> positionToOffset(StringRef Code, Position P,
bool AllowColumnsBeyondLineLength) {
llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
bool AllowColumnsBeyondLineLength) {
if (P.line < 0)
return make_error<StringError>(
formatv("Line value can't be negative ({0})", P.line),
errc::invalid_argument);
return llvm::make_error<llvm::StringError>(
llvm::formatv("Line value can't be negative ({0})", P.line),
llvm::errc::invalid_argument);
if (P.character < 0)
return make_error<StringError>(
formatv("Character value can't be negative ({0})", P.character),
errc::invalid_argument);
return llvm::make_error<llvm::StringError>(
llvm::formatv("Character value can't be negative ({0})", P.character),
llvm::errc::invalid_argument);
size_t StartOfLine = 0;
for (int I = 0; I != P.line; ++I) {
size_t NextNL = Code.find('\n', StartOfLine);
if (NextNL == StringRef::npos)
return make_error<StringError>(
formatv("Line value is out of range ({0})", P.line),
errc::invalid_argument);
if (NextNL == llvm::StringRef::npos)
return llvm::make_error<llvm::StringError>(
llvm::formatv("Line value is out of range ({0})", P.line),
llvm::errc::invalid_argument);
StartOfLine = NextNL + 1;
}

size_t NextNL = Code.find('\n', StartOfLine);
if (NextNL == StringRef::npos)
if (NextNL == llvm::StringRef::npos)
NextNL = Code.size();

bool Valid;
size_t ByteOffsetInLine = measureUTF16(
Code.substr(StartOfLine, NextNL - StartOfLine), P.character, Valid);
if (!Valid && !AllowColumnsBeyondLineLength)
return make_error<StringError>(
formatv("UTF-16 offset {0} is invalid for line {1}", P.character,
P.line),
errc::invalid_argument);
return llvm::make_error<llvm::StringError>(
llvm::formatv("UTF-16 offset {0} is invalid for line {1}", P.character,
P.line),
llvm::errc::invalid_argument);
return StartOfLine + ByteOffsetInLine;
}

Position offsetToPosition(StringRef Code, size_t Offset) {
Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
Offset = std::min(Code.size(), Offset);
StringRef Before = Code.substr(0, Offset);
llvm::StringRef Before = Code.substr(0, Offset);
int Lines = Before.count('\n');
size_t PrevNL = Before.rfind('\n');
size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Position Pos;
Pos.line = Lines;
Pos.character = lspLength(Before.substr(StartOfLine));
Expand All @@ -134,7 +133,7 @@ Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
Position P;
P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
bool Invalid = false;
StringRef Code = SM.getBufferData(FID, &Invalid);
llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
if (!Invalid) {
auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
Expand All @@ -151,45 +150,47 @@ Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
return {Begin, End};
}

std::pair<size_t, size_t> offsetToClangLineColumn(StringRef Code,
std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
size_t Offset) {
Offset = std::min(Code.size(), Offset);
StringRef Before = Code.substr(0, Offset);
llvm::StringRef Before = Code.substr(0, Offset);
int Lines = Before.count('\n');
size_t PrevNL = Before.rfind('\n');
size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
return {Lines + 1, Offset - StartOfLine + 1};
}

std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
std::pair<llvm::StringRef, llvm::StringRef>
splitQualifiedName(llvm::StringRef QName) {
size_t Pos = QName.rfind("::");
if (Pos == StringRef::npos)
return {StringRef(), QName};
if (Pos == llvm::StringRef::npos)
return {llvm::StringRef(), QName};
return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
}

TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R) {
TextEdit replacementToEdit(llvm::StringRef Code,
const tooling::Replacement &R) {
Range ReplacementRange = {
offsetToPosition(Code, R.getOffset()),
offsetToPosition(Code, R.getOffset() + R.getLength())};
return {ReplacementRange, R.getReplacementText()};
}

std::vector<TextEdit> replacementsToEdits(StringRef Code,
std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
const tooling::Replacements &Repls) {
std::vector<TextEdit> Edits;
for (const auto &R : Repls)
Edits.push_back(replacementToEdit(Code, R));
return Edits;
}

Optional<std::string> getCanonicalPath(const FileEntry *F,
const SourceManager &SourceMgr) {
llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
const SourceManager &SourceMgr) {
if (!F)
return None;

SmallString<128> FilePath = F->getName();
if (!sys::path::is_absolute(FilePath)) {
llvm::SmallString<128> FilePath = F->getName();
if (!llvm::sys::path::is_absolute(FilePath)) {
if (auto EC =
SourceMgr.getFileManager().getVirtualFileSystem()->makeAbsolute(
FilePath)) {
Expand All @@ -211,10 +212,11 @@ Optional<std::string> getCanonicalPath(const FileEntry *F,
// The file path of Symbol is "/project/src/foo.h" instead of
// "/tmp/build/foo.h"
if (const DirectoryEntry *Dir = SourceMgr.getFileManager().getDirectory(
sys::path::parent_path(FilePath))) {
SmallString<128> RealPath;
StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
sys::path::append(RealPath, DirName, sys::path::filename(FilePath));
llvm::sys::path::parent_path(FilePath))) {
llvm::SmallString<128> RealPath;
llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
llvm::sys::path::append(RealPath, DirName,
llvm::sys::path::filename(FilePath));
return RealPath.str().str();
}

Expand All @@ -235,13 +237,13 @@ bool IsRangeConsecutive(const Range &Left, const Range &Right) {
Left.end.character == Right.start.character;
}

FileDigest digest(StringRef Content) {
FileDigest digest(llvm::StringRef Content) {
return llvm::SHA1::hash({(const uint8_t *)Content.data(), Content.size()});
}

Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
bool Invalid = false;
StringRef Content = SM.getBufferData(FID, &Invalid);
llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
if (Invalid)
return None;
return digest(Content);
Expand Down
86 changes: 45 additions & 41 deletions clang-tools-extra/clangd/TUScheduler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@
#include <queue>
#include <thread>

using namespace llvm;
namespace clang {
namespace clangd {
using std::chrono::steady_clock;
Expand All @@ -67,9 +66,9 @@ class ASTWorker;

static clang::clangd::Key<std::string> kFileBeingProcessed;

Optional<StringRef> TUScheduler::getFileBeingProcessedInContext() {
llvm::Optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
if (auto *File = Context::current().get(kFileBeingProcessed))
return StringRef(*File);
return llvm::StringRef(*File);
return None;
}

Expand Down Expand Up @@ -113,7 +112,7 @@ class TUScheduler::ASTCache {
/// Returns the cached value for \p K, or llvm::None if the value is not in
/// the cache anymore. If nullptr was cached for \p K, this function will
/// return a null unique_ptr wrapped into an optional.
Optional<std::unique_ptr<ParsedAST>> take(Key K) {
llvm::Optional<std::unique_ptr<ParsedAST>> take(Key K) {
std::unique_lock<std::mutex> Lock(Mut);
auto Existing = findByKey(K);
if (Existing == LRU.end())
Expand All @@ -123,7 +122,7 @@ class TUScheduler::ASTCache {
// GCC 4.8 fails to compile `return V;`, as it tries to call the copy
// constructor of unique_ptr, so we call the move ctor explicitly to avoid
// this miscompile.
return Optional<std::unique_ptr<ParsedAST>>(std::move(V));
return llvm::Optional<std::unique_ptr<ParsedAST>>(std::move(V));
}

private:
Expand Down Expand Up @@ -177,15 +176,16 @@ class ASTWorker {
~ASTWorker();

void update(ParseInputs Inputs, WantDiagnostics);
void runWithAST(StringRef Name,
unique_function<void(Expected<InputsAndAST>)> Action);
void
runWithAST(llvm::StringRef Name,
llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action);
bool blockUntilIdle(Deadline Timeout) const;

std::shared_ptr<const PreambleData> getPossiblyStalePreamble() const;
/// Obtain a preamble reflecting all updates so far. Threadsafe.
/// It may be delivered immediately, or later on the worker thread.
void getCurrentPreamble(
unique_function<void(std::shared_ptr<const PreambleData>)>);
llvm::unique_function<void(std::shared_ptr<const PreambleData>)>);
/// Wait for the first build of preamble to finish. Preamble itself can be
/// accessed via getPossiblyStalePreamble(). Note that this function will
/// return after an unsuccessful build of the preamble too, i.e. result of
Expand All @@ -203,8 +203,8 @@ class ASTWorker {
/// Signal that run() should finish processing pending requests and exit.
void stop();
/// Adds a new task to the end of the request queue.
void startTask(StringRef Name, unique_function<void()> Task,
Optional<WantDiagnostics> UpdateType);
void startTask(llvm::StringRef Name, llvm::unique_function<void()> Task,
llvm::Optional<WantDiagnostics> UpdateType);
/// Updates the TUStatus and emits it. Only called in the worker thread.
void emitTUStatus(TUAction FAction,
const TUStatus::BuildDetails *Detail = nullptr);
Expand All @@ -218,11 +218,11 @@ class ASTWorker {
bool shouldSkipHeadLocked() const;

struct Request {
unique_function<void()> Action;
llvm::unique_function<void()> Action;
std::string Name;
steady_clock::time_point AddTime;
Context Ctx;
Optional<WantDiagnostics> UpdateType;
llvm::Optional<WantDiagnostics> UpdateType;
};

/// Handles retention of ASTs.
Expand Down Expand Up @@ -321,7 +321,7 @@ ASTWorkerHandle ASTWorker::create(PathRef FileName,
FileName, IdleASTs, Barrier, /*RunSync=*/!Tasks, UpdateDebounce,
std::move(PCHs), StorePreamblesInMemory, Callbacks));
if (Tasks)
Tasks->runAsync("worker:" + sys::path::filename(FileName),
Tasks->runAsync("worker:" + llvm::sys::path::filename(FileName),
[Worker]() { Worker->run(); });

return ASTWorkerHandle(std::move(Worker));
Expand Down Expand Up @@ -350,7 +350,7 @@ ASTWorker::~ASTWorker() {
}

void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags) {
StringRef TaskName = "Update";
llvm::StringRef TaskName = "Update";
auto Task = [=]() mutable {
// Will be used to check if we can avoid rebuilding the AST.
bool InputsAreTheSame =
Expand All @@ -364,7 +364,7 @@ void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags) {
emitTUStatus({TUAction::BuildingPreamble, TaskName});
log("Updating file {0} with command [{1}] {2}", FileName,
Inputs.CompileCommand.Directory,
join(Inputs.CompileCommand.CommandLine, " "));
llvm::join(Inputs.CompileCommand.CommandLine, " "));
// Rebuild the preamble and the AST.
std::unique_ptr<CompilerInvocation> Invocation =
buildCompilerInvocation(Inputs);
Expand Down Expand Up @@ -437,9 +437,9 @@ void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags) {
}

// Get the AST for diagnostics.
Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
llvm::Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
if (!AST) {
Optional<ParsedAST> NewAST =
llvm::Optional<ParsedAST> NewAST =
buildAST(FileName, std::move(Invocation), Inputs, NewPreamble, PCHs);
AST = NewAST ? llvm::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
if (!(*AST)) { // buildAST fails.
Expand Down Expand Up @@ -474,16 +474,17 @@ void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags) {
}

void ASTWorker::runWithAST(
StringRef Name, unique_function<void(Expected<InputsAndAST>)> Action) {
llvm::StringRef Name,
llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action) {
auto Task = [=](decltype(Action) Action) {
if (isCancelled())
return Action(make_error<CancelledError>());
Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
return Action(llvm::make_error<CancelledError>());
llvm::Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
if (!AST) {
std::unique_ptr<CompilerInvocation> Invocation =
buildCompilerInvocation(FileInputs);
// Try rebuilding the AST.
Optional<ParsedAST> NewAST =
llvm::Optional<ParsedAST> NewAST =
Invocation
? buildAST(FileName,
llvm::make_unique<CompilerInvocation>(*Invocation),
Expand All @@ -492,12 +493,12 @@ void ASTWorker::runWithAST(
AST = NewAST ? llvm::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
}
// Make sure we put the AST back into the LRU cache.
auto _ = make_scope_exit(
auto _ = llvm::make_scope_exit(
[&AST, this]() { IdleASTs.put(this, std::move(*AST)); });
// Run the user-provided action.
if (!*AST)
return Action(
make_error<StringError>("invalid AST", errc::invalid_argument));
return Action(llvm::make_error<llvm::StringError>(
"invalid AST", llvm::errc::invalid_argument));
Action(InputsAndAST{FileInputs, **AST});
};
startTask(Name, Bind(Task, std::move(Action)),
Expand All @@ -511,7 +512,7 @@ ASTWorker::getPossiblyStalePreamble() const {
}

void ASTWorker::getCurrentPreamble(
unique_function<void(std::shared_ptr<const PreambleData>)> Callback) {
llvm::unique_function<void(std::shared_ptr<const PreambleData>)> Callback) {
// We could just call startTask() to throw the read on the queue, knowing
// it will run after any updates. But we know this task is cheap, so to
// improve latency we cheat: insert it on the queue after the last update.
Expand Down Expand Up @@ -565,11 +566,12 @@ void ASTWorker::stop() {
RequestsCV.notify_all();
}

void ASTWorker::startTask(StringRef Name, unique_function<void()> Task,
Optional<WantDiagnostics> UpdateType) {
void ASTWorker::startTask(llvm::StringRef Name,
llvm::unique_function<void()> Task,
llvm::Optional<WantDiagnostics> UpdateType) {
if (RunSync) {
assert(!Done && "running a task after stop()");
trace::Span Tracer(Name + ":" + sys::path::filename(FileName));
trace::Span Tracer(Name + ":" + llvm::sys::path::filename(FileName));
Task();
return;
}
Expand Down Expand Up @@ -611,8 +613,8 @@ void ASTWorker::run() {
}

// Tracing: we have a next request, attribute this sleep to it.
Optional<WithContext> Ctx;
Optional<trace::Span> Tracer;
llvm::Optional<WithContext> Ctx;
llvm::Optional<trace::Span> Tracer;
if (!Requests.empty()) {
Ctx.emplace(Requests.front().Ctx.clone());
Tracer.emplace("Debounce");
Expand Down Expand Up @@ -734,7 +736,7 @@ bool ASTWorker::blockUntilIdle(Deadline Timeout) const {
// are familiar by C++ programmers.
std::string renderTUAction(const TUAction &Action) {
std::string Result;
raw_string_ostream OS(Result);
llvm::raw_string_ostream OS(Result);
switch (Action.S) {
case TUAction::Queued:
OS << "file is queued";
Expand Down Expand Up @@ -844,32 +846,34 @@ void TUScheduler::remove(PathRef File) {
File);
}

void TUScheduler::run(StringRef Name, unique_function<void()> Action) {
void TUScheduler::run(llvm::StringRef Name,
llvm::unique_function<void()> Action) {
if (!PreambleTasks)
return Action();
PreambleTasks->runAsync(Name, std::move(Action));
}

void TUScheduler::runWithAST(
StringRef Name, PathRef File,
unique_function<void(Expected<InputsAndAST>)> Action) {
llvm::StringRef Name, PathRef File,
llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action) {
auto It = Files.find(File);
if (It == Files.end()) {
Action(make_error<LSPError>("trying to get AST for non-added document",
ErrorCode::InvalidParams));
Action(llvm::make_error<LSPError>(
"trying to get AST for non-added document", ErrorCode::InvalidParams));
return;
}

It->second->Worker->runWithAST(Name, std::move(Action));
}

void TUScheduler::runWithPreamble(
StringRef Name, PathRef File, PreambleConsistency Consistency,
unique_function<void(Expected<InputsAndPreamble>)> Action) {
llvm::StringRef Name, PathRef File, PreambleConsistency Consistency,
llvm::unique_function<void(llvm::Expected<InputsAndPreamble>)> Action) {
auto It = Files.find(File);
if (It == Files.end()) {
Action(make_error<LSPError>("trying to get preamble for non-added document",
ErrorCode::InvalidParams));
Action(llvm::make_error<LSPError>(
"trying to get preamble for non-added document",
ErrorCode::InvalidParams));
return;
}

Expand Down Expand Up @@ -921,7 +925,7 @@ void TUScheduler::runWithPreamble(
};

PreambleTasks->runAsync(
"task:" + sys::path::filename(File),
"task:" + llvm::sys::path::filename(File),
Bind(Task, std::string(Name), std::string(File), It->second->Contents,
It->second->Command,
Context::current().derive(kFileBeingProcessed, File),
Expand Down
11 changes: 5 additions & 6 deletions clang-tools-extra/clangd/Threading.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
#include <pthread.h>
#endif

using namespace llvm;
namespace clang {
namespace clangd {

Expand Down Expand Up @@ -64,14 +63,14 @@ bool AsyncTaskRunner::wait(Deadline D) const {
[&] { return InFlightTasks == 0; });
}

void AsyncTaskRunner::runAsync(const Twine &Name,
unique_function<void()> Action) {
void AsyncTaskRunner::runAsync(const llvm::Twine &Name,
llvm::unique_function<void()> Action) {
{
std::lock_guard<std::mutex> Lock(Mutex);
++InFlightTasks;
}

auto CleanupTask = make_scope_exit([this]() {
auto CleanupTask = llvm::make_scope_exit([this]() {
std::lock_guard<std::mutex> Lock(Mutex);
int NewTasksCnt = --InFlightTasks;
if (NewTasksCnt == 0) {
Expand All @@ -83,7 +82,7 @@ void AsyncTaskRunner::runAsync(const Twine &Name,

std::thread(
[](std::string Name, decltype(Action) Action, decltype(CleanupTask)) {
set_thread_name(Name);
llvm::set_thread_name(Name);
Action();
// Make sure function stored by Action is destroyed before CleanupTask
// is run.
Expand All @@ -93,7 +92,7 @@ void AsyncTaskRunner::runAsync(const Twine &Name,
.detach();
}

Deadline timeoutSeconds(Optional<double> Seconds) {
Deadline timeoutSeconds(llvm::Optional<double> Seconds) {
using namespace std::chrono;
if (!Seconds)
return Deadline::infinity();
Expand Down
Loading