[clang-tools-extra] r350531 - [clangd] Remove 'using namespace llvm' from .cpp files. NFC

Ilya Biryukov via cfe-commits cfe-commits at lists.llvm.org
Mon Jan 7 07:45:19 PST 2019


Author: ibiryukov
Date: Mon Jan  7 07:45:19 2019
New Revision: 350531

URL: http://llvm.org/viewvc/llvm-project?rev=350531&view=rev
Log:
[clangd] Remove 'using namespace llvm' from .cpp files. NFC

The new guideline is to qualify with 'llvm::' explicitly both in
'.h' and '.cpp' files. This simplifies moving the code between
header and source files and is easier to keep consistent.

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/ExpectedTypes.cpp
    clang-tools-extra/trunk/clangd/FS.cpp
    clang-tools-extra/trunk/clangd/FSProvider.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/SymbolID.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/BackgroundIndexTests.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/ExpectedTypeTest.cpp
    clang-tools-extra/trunk/unittests/clangd/FSTests.cpp
    clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp
    clang-tools-extra/trunk/unittests/clangd/FindSymbolsTests.cpp
    clang-tools-extra/trunk/unittests/clangd/FunctionTests.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/IndexActionTests.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/SymbolInfoTests.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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/AST.cpp (original)
+++ clang-tools-extra/trunk/clangd/AST.cpp Mon Jan  7 07:45:19 2019
@@ -18,7 +18,6 @@
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ScopedPrinter.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -35,8 +34,8 @@ bool isSpelledInSourceCode(const Decl *D
   // macros, we should use the location where the whole definition occurs.
   if (Loc.isMacroID()) {
     std::string PrintLoc = SM.getSpellingLoc(Loc).printToString(SM);
-    if (StringRef(PrintLoc).startswith("<scratch") ||
-        StringRef(PrintLoc).startswith("<command line>"))
+    if (llvm::StringRef(PrintLoc).startswith("<scratch") ||
+        llvm::StringRef(PrintLoc).startswith("<command line>"))
       return false;
   }
   return true;
@@ -54,7 +53,7 @@ SourceLocation findNameLoc(const clang::
 
 std::string printQualifiedName(const NamedDecl &ND) {
   std::string QName;
-  raw_string_ostream OS(QName);
+  llvm::raw_string_ostream OS(QName);
   PrintingPolicy Policy(ND.getASTContext().getLangOpts());
   // Note that inline namespaces are treated as transparent scopes. This
   // reflects the way they're most commonly used for lookup. Ideally we'd
@@ -115,18 +114,19 @@ std::string printNamespaceScope(const De
   return "";
 }
 
-Optional<SymbolID> getSymbolID(const Decl *D) {
-  SmallString<128> USR;
+llvm::Optional<SymbolID> getSymbolID(const Decl *D) {
+  llvm::SmallString<128> USR;
   if (index::generateUSRForDecl(D, USR))
     return None;
   return SymbolID(USR);
 }
 
-Optional<SymbolID> getSymbolID(const IdentifierInfo &II, const MacroInfo *MI,
-                               const SourceManager &SM) {
+llvm::Optional<SymbolID> getSymbolID(const IdentifierInfo &II,
+                                     const MacroInfo *MI,
+                                     const SourceManager &SM) {
   if (MI == nullptr)
     return None;
-  SmallString<128> USR;
+  llvm::SmallString<128> USR;
   if (index::generateUSRForMacro(II.getName(), MI->getDefinitionLoc(), SM, USR))
     return None;
   return SymbolID(USR);

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Mon Jan  7 07:45:19 2019
@@ -18,7 +18,6 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -69,7 +68,7 @@ class ClangdLSPServer::MessageHandler :
 public:
   MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
 
-  bool onNotify(StringRef Method, json::Value Params) override {
+  bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
     log("<-- {0}", Method);
     if (Method == "exit")
       return false;
@@ -84,7 +83,8 @@ public:
     return true;
   }
 
-  bool onCall(StringRef Method, json::Value Params, json::Value ID) override {
+  bool onCall(llvm::StringRef Method, llvm::json::Value Params,
+              llvm::json::Value ID) override {
     // Calls can be canceled by the client. Add cancellation context.
     WithContext WithCancel(cancelableRequestContext(ID));
     trace::Span Tracer(Method);
@@ -93,22 +93,23 @@ public:
     log("<-- {0}({1})", Method, ID);
     if (!Server.Server && Method != "initialize") {
       elog("Call {0} before initialization.", Method);
-      Reply(make_error<LSPError>("server not initialized",
-                                 ErrorCode::ServerNotInitialized));
+      Reply(llvm::make_error<LSPError>("server not initialized",
+                                       ErrorCode::ServerNotInitialized));
     } else if (auto Handler = Calls.lookup(Method))
       Handler(std::move(Params), std::move(Reply));
     else
-      Reply(
-          make_error<LSPError>("method not found", ErrorCode::MethodNotFound));
+      Reply(llvm::make_error<LSPError>("method not found",
+                                       ErrorCode::MethodNotFound));
     return true;
   }
 
-  bool onReply(json::Value ID, Expected<json::Value> Result) override {
+  bool onReply(llvm::json::Value ID,
+               llvm::Expected<llvm::json::Value> Result) override {
     // We ignore replies, just log them.
     if (Result)
       log("<-- reply({0})", ID);
     else
-      log("<-- reply({0}) error: {1}", ID, toString(Result.takeError()));
+      log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
     return true;
   }
 
@@ -116,15 +117,15 @@ public:
   template <typename Param, typename Result>
   void bind(const char *Method,
             void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
-    Calls[Method] = [Method, Handler, this](json::Value RawParams,
+    Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
                                             ReplyOnce Reply) {
       Param P;
       if (fromJSON(RawParams, P)) {
         (Server.*Handler)(P, std::move(Reply));
       } else {
         elog("Failed to decode {0} request.", Method);
-        Reply(make_error<LSPError>("failed to decode request",
-                                   ErrorCode::InvalidRequest));
+        Reply(llvm::make_error<LSPError>("failed to decode request",
+                                         ErrorCode::InvalidRequest));
       }
     };
   }
@@ -133,7 +134,8 @@ public:
   template <typename Param>
   void bind(const char *Method,
             void (ClangdLSPServer::*Handler)(const Param &)) {
-    Notifications[Method] = [Method, Handler, this](json::Value RawParams) {
+    Notifications[Method] = [Method, Handler,
+                             this](llvm::json::Value RawParams) {
       Param P;
       if (!fromJSON(RawParams, P)) {
         elog("Failed to decode {0} request.", Method);
@@ -154,14 +156,14 @@ private:
   class ReplyOnce {
     std::atomic<bool> Replied = {false};
     std::chrono::steady_clock::time_point Start;
-    json::Value ID;
+    llvm::json::Value ID;
     std::string Method;
     ClangdLSPServer *Server; // Null when moved-from.
-    json::Object *TraceArgs;
+    llvm::json::Object *TraceArgs;
 
   public:
-    ReplyOnce(const json::Value &ID, StringRef Method, ClangdLSPServer *Server,
-              json::Object *TraceArgs)
+    ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
+              ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
         : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
           Server(Server), TraceArgs(TraceArgs) {
       assert(Server);
@@ -180,12 +182,12 @@ private:
       if (Server && !Replied) {
         elog("No reply to message {0}({1})", Method, ID);
         assert(false && "must reply to all calls!");
-        (*this)(make_error<LSPError>("server failed to reply",
-                                     ErrorCode::InternalError));
+        (*this)(llvm::make_error<LSPError>("server failed to reply",
+                                           ErrorCode::InternalError));
       }
     }
 
-    void operator()(Expected<json::Value> Reply) {
+    void operator()(llvm::Expected<llvm::json::Value> Reply) {
       assert(Server && "moved-from!");
       if (Replied.exchange(true)) {
         elog("Replied twice to message {0}({1})", Method, ID);
@@ -200,34 +202,34 @@ private:
         std::lock_guard<std::mutex> Lock(Server->TranspWriter);
         Server->Transp.reply(std::move(ID), std::move(Reply));
       } else {
-        Error Err = Reply.takeError();
+        llvm::Error Err = Reply.takeError();
         log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
         if (TraceArgs)
-          (*TraceArgs)["Error"] = to_string(Err);
+          (*TraceArgs)["Error"] = llvm::to_string(Err);
         std::lock_guard<std::mutex> Lock(Server->TranspWriter);
         Server->Transp.reply(std::move(ID), std::move(Err));
       }
     }
   };
 
-  StringMap<std::function<void(json::Value)>> Notifications;
-  StringMap<std::function<void(json::Value, ReplyOnce)>> Calls;
+  llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
+  llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
 
   // Method calls may be cancelled by ID, so keep track of their state.
   // This needs a mutex: handlers may finish on a different thread, and that's
   // when we clean up entries in the map.
   mutable std::mutex RequestCancelersMutex;
-  StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
+  llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
   unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
-  void onCancel(const json::Value &Params) {
-    const json::Value *ID = nullptr;
+  void onCancel(const llvm::json::Value &Params) {
+    const llvm::json::Value *ID = nullptr;
     if (auto *O = Params.getAsObject())
       ID = O->get("id");
     if (!ID) {
       elog("Bad cancellation request: {0}", Params);
       return;
     }
-    auto StrID = to_string(*ID);
+    auto StrID = llvm::to_string(*ID);
     std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
     auto It = RequestCancelers.find(StrID);
     if (It != RequestCancelers.end())
@@ -237,9 +239,9 @@ private:
   //  - allows cancellation using RequestCancelers[ID]
   //  - cleans up the entry in RequestCancelers when it's no longer needed
   // If a client reuses an ID, the last wins and the first cannot be canceled.
-  Context cancelableRequestContext(const json::Value &ID) {
+  Context cancelableRequestContext(const llvm::json::Value &ID) {
     auto Task = cancelableTask();
-    auto StrID = to_string(ID);        // JSON-serialize ID for map key.
+    auto StrID = llvm::to_string(ID);  // JSON-serialize ID for map key.
     auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
     {
       std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
@@ -248,7 +250,7 @@ private:
     // When the request ends, we can clean up the entry we just added.
     // The cookie lets us check that it hasn't been overwritten due to ID
     // reuse.
-    return Task.first.derive(make_scope_exit([this, StrID, Cookie] {
+    return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
       std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
       auto It = RequestCancelers.find(StrID);
       if (It != RequestCancelers.end() && It->second.second == Cookie)
@@ -260,7 +262,7 @@ private:
 };
 
 // call(), notify(), and reply() wrap the Transport, adding logging and locking.
-void ClangdLSPServer::call(StringRef Method, json::Value Params) {
+void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
   auto ID = NextCallID++;
   log("--> {0}({1})", Method, ID);
   // We currently don't handle responses, so no need to store ID anywhere.
@@ -268,21 +270,21 @@ void ClangdLSPServer::call(StringRef Met
   Transp.call(Method, std::move(Params), ID);
 }
 
-void ClangdLSPServer::notify(StringRef Method, json::Value Params) {
+void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
   log("--> {0}", Method);
   std::lock_guard<std::mutex> Lock(TranspWriter);
   Transp.notify(Method, std::move(Params));
 }
 
 void ClangdLSPServer::onInitialize(const InitializeParams &Params,
-                                   Callback<json::Value> Reply) {
+                                   Callback<llvm::json::Value> Reply) {
   if (Params.rootUri && *Params.rootUri)
     ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
   else if (Params.rootPath && !Params.rootPath->empty())
     ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
   if (Server)
-    return Reply(make_error<LSPError>("server already initialized",
-                                      ErrorCode::InvalidRequest));
+    return Reply(llvm::make_error<LSPError>("server already initialized",
+                                            ErrorCode::InvalidRequest));
   if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
     CompileCommandsDir = Dir;
   if (UseDirBasedCDB)
@@ -304,27 +306,27 @@ void ClangdLSPServer::onInitialize(const
   SupportsHierarchicalDocumentSymbol =
       Params.capabilities.HierarchicalDocumentSymbol;
   SupportFileStatus = Params.initializationOptions.FileStatus;
-  Reply(json::Object{
+  Reply(llvm::json::Object{
       {{"capabilities",
-        json::Object{
+        llvm::json::Object{
             {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
             {"documentFormattingProvider", true},
             {"documentRangeFormattingProvider", true},
             {"documentOnTypeFormattingProvider",
-             json::Object{
+             llvm::json::Object{
                  {"firstTriggerCharacter", "}"},
                  {"moreTriggerCharacter", {}},
              }},
             {"codeActionProvider", true},
             {"completionProvider",
-             json::Object{
+             llvm::json::Object{
                  {"resolveProvider", false},
                  // We do extra checks for '>' and ':' in completion to only
                  // trigger on '->' and '::'.
                  {"triggerCharacters", {".", ">", ":"}},
              }},
             {"signatureHelpProvider",
-             json::Object{
+             llvm::json::Object{
                  {"triggerCharacters", {"(", ","}},
              }},
             {"definitionProvider", true},
@@ -335,7 +337,7 @@ void ClangdLSPServer::onInitialize(const
             {"workspaceSymbolProvider", true},
             {"referencesProvider", true},
             {"executeCommandProvider",
-             json::Object{
+             llvm::json::Object{
                  {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
              }},
         }}}});
@@ -355,8 +357,8 @@ void ClangdLSPServer::onSync(const NoPar
   if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
     Reply(nullptr);
   else
-    Reply(createStringError(llvm::inconvertibleErrorCode(),
-                            "Not idle after a minute"));
+    Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
+                                  "Not idle after a minute"));
 }
 
 void ClangdLSPServer::onDocumentDidOpen(
@@ -377,7 +379,7 @@ void ClangdLSPServer::onDocumentDidChang
                                                   : WantDiagnostics::No;
 
   PathRef File = Params.textDocument.uri.file();
-  Expected<std::string> Contents =
+  llvm::Expected<std::string> Contents =
       DraftMgr.updateDraft(File, Params.contentChanges);
   if (!Contents) {
     // If this fails, we are most likely going to be not in sync anymore with
@@ -397,7 +399,7 @@ void ClangdLSPServer::onFileEvent(const
 }
 
 void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
-                                Callback<json::Value> Reply) {
+                                Callback<llvm::json::Value> Reply) {
   auto ApplyEdit = [&](WorkspaceEdit WE) {
     ApplyWorkspaceEditParams Edit;
     Edit.edit = std::move(WE);
@@ -422,8 +424,8 @@ void ClangdLSPServer::onCommand(const Ex
     // We should not get here because ExecuteCommandParams would not have
     // parsed in the first place and this handler should not be called. But if
     // more commands are added, this will be here has a safe guard.
-    Reply(make_error<LSPError>(
-        formatv("Unsupported command \"{0}\".", Params.command).str(),
+    Reply(llvm::make_error<LSPError>(
+        llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
         ErrorCode::InvalidParams));
   }
 }
@@ -435,7 +437,7 @@ void ClangdLSPServer::onWorkspaceSymbol(
       Params.query, CCOpts.Limit,
       Bind(
           [this](decltype(Reply) Reply,
-                 Expected<std::vector<SymbolInformation>> Items) {
+                 llvm::Expected<std::vector<SymbolInformation>> Items) {
             if (!Items)
               return Reply(Items.takeError());
             for (auto &Sym : *Items)
@@ -449,17 +451,17 @@ void ClangdLSPServer::onWorkspaceSymbol(
 void ClangdLSPServer::onRename(const RenameParams &Params,
                                Callback<WorkspaceEdit> Reply) {
   Path File = Params.textDocument.uri.file();
-  Optional<std::string> Code = DraftMgr.getDraft(File);
+  llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
   if (!Code)
-    return Reply(make_error<LSPError>("onRename called for non-added file",
-                                      ErrorCode::InvalidParams));
+    return Reply(llvm::make_error<LSPError>(
+        "onRename called for non-added file", ErrorCode::InvalidParams));
 
   Server->rename(
       File, Params.position, Params.newName,
       Bind(
-          [File, Code,
-           Params](decltype(Reply) Reply,
-                   Expected<std::vector<tooling::Replacement>> Replacements) {
+          [File, Code, Params](
+              decltype(Reply) Reply,
+              llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
             if (!Replacements)
               return Reply(Replacements.takeError());
 
@@ -488,7 +490,7 @@ void ClangdLSPServer::onDocumentOnTypeFo
   auto File = Params.textDocument.uri.file();
   auto Code = DraftMgr.getDraft(File);
   if (!Code)
-    return Reply(make_error<LSPError>(
+    return Reply(llvm::make_error<LSPError>(
         "onDocumentOnTypeFormatting called for non-added file",
         ErrorCode::InvalidParams));
 
@@ -505,7 +507,7 @@ void ClangdLSPServer::onDocumentRangeFor
   auto File = Params.textDocument.uri.file();
   auto Code = DraftMgr.getDraft(File);
   if (!Code)
-    return Reply(make_error<LSPError>(
+    return Reply(llvm::make_error<LSPError>(
         "onDocumentRangeFormatting called for non-added file",
         ErrorCode::InvalidParams));
 
@@ -522,9 +524,9 @@ void ClangdLSPServer::onDocumentFormatti
   auto File = Params.textDocument.uri.file();
   auto Code = DraftMgr.getDraft(File);
   if (!Code)
-    return Reply(
-        make_error<LSPError>("onDocumentFormatting called for non-added file",
-                             ErrorCode::InvalidParams));
+    return Reply(llvm::make_error<LSPError>(
+        "onDocumentFormatting called for non-added file",
+        ErrorCode::InvalidParams));
 
   auto ReplacementsOrError = Server->formatFile(*Code, File);
   if (ReplacementsOrError)
@@ -540,8 +542,8 @@ flattenSymbolHierarchy(llvm::ArrayRef<Do
                        const URIForFile &FileURI) {
 
   std::vector<SymbolInformation> Results;
-  std::function<void(const DocumentSymbol &, StringRef)> Process =
-      [&](const DocumentSymbol &S, Optional<StringRef> ParentName) {
+  std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
+      [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
         SymbolInformation SI;
         SI.containerName = ParentName ? "" : *ParentName;
         SI.name = S.name;
@@ -561,13 +563,13 @@ flattenSymbolHierarchy(llvm::ArrayRef<Do
 }
 
 void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
-                                       Callback<json::Value> Reply) {
+                                       Callback<llvm::json::Value> Reply) {
   URIForFile FileURI = Params.textDocument.uri;
   Server->documentSymbols(
       Params.textDocument.uri.file(),
       Bind(
           [this, FileURI](decltype(Reply) Reply,
-                          Expected<std::vector<DocumentSymbol>> Items) {
+                          llvm::Expected<std::vector<DocumentSymbol>> Items) {
             if (!Items)
               return Reply(Items.takeError());
             adjustSymbolKinds(*Items, SupportedSymbolKinds);
@@ -579,7 +581,7 @@ void ClangdLSPServer::onDocumentSymbol(c
           std::move(Reply)));
 }
 
-static Optional<Command> asCommand(const CodeAction &Action) {
+static llvm::Optional<Command> asCommand(const CodeAction &Action) {
   Command Cmd;
   if (Action.command && Action.edit)
     return None; // Not representable. (We never emit these anyway).
@@ -598,11 +600,11 @@ static Optional<Command> asCommand(const
 }
 
 void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
-                                   Callback<json::Value> Reply) {
+                                   Callback<llvm::json::Value> Reply) {
   auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
   if (!Code)
-    return Reply(make_error<LSPError>("onCodeAction called for non-added file",
-                                      ErrorCode::InvalidParams));
+    return Reply(llvm::make_error<LSPError>(
+        "onCodeAction called for non-added file", ErrorCode::InvalidParams));
   // We provide a code action for Fixes on the specified diagnostics.
   std::vector<CodeAction> Actions;
   for (const Diagnostic &D : Params.context.diagnostics) {
@@ -613,13 +615,13 @@ void ClangdLSPServer::onCodeAction(const
   }
 
   if (SupportsCodeAction)
-    Reply(json::Array(Actions));
+    Reply(llvm::json::Array(Actions));
   else {
     std::vector<Command> Commands;
     for (const auto &Action : Actions)
       if (auto Command = asCommand(Action))
         Commands.push_back(std::move(*Command));
-    Reply(json::Array(Commands));
+    Reply(llvm::json::Array(Commands));
   }
 }
 
@@ -627,23 +629,23 @@ void ClangdLSPServer::onCompletion(const
                                    Callback<CompletionList> Reply) {
   if (!shouldRunCompletion(Params))
     return Reply(llvm::make_error<IgnoreCompletionError>());
-  Server->codeComplete(
-      Params.textDocument.uri.file(), Params.position, CCOpts,
-      Bind(
-          [this](decltype(Reply) Reply, Expected<CodeCompleteResult> List) {
-            if (!List)
-              return Reply(List.takeError());
-            CompletionList LSPList;
-            LSPList.isIncomplete = List->HasMore;
-            for (const auto &R : List->Completions) {
-              CompletionItem C = R.render(CCOpts);
-              C.kind =
-                  adjustKindToCapability(C.kind, SupportedCompletionItemKinds);
-              LSPList.items.push_back(std::move(C));
-            }
-            return Reply(std::move(LSPList));
-          },
-          std::move(Reply)));
+  Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
+                       Bind(
+                           [this](decltype(Reply) Reply,
+                                  llvm::Expected<CodeCompleteResult> List) {
+                             if (!List)
+                               return Reply(List.takeError());
+                             CompletionList LSPList;
+                             LSPList.isIncomplete = List->HasMore;
+                             for (const auto &R : List->Completions) {
+                               CompletionItem C = R.render(CCOpts);
+                               C.kind = adjustKindToCapability(
+                                   C.kind, SupportedCompletionItemKinds);
+                               LSPList.items.push_back(std::move(C));
+                             }
+                             return Reply(std::move(LSPList));
+                           },
+                           std::move(Reply)));
 }
 
 void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
@@ -660,7 +662,7 @@ void ClangdLSPServer::onGoToDefinition(c
 
 void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
                                            Callback<std::string> Reply) {
-  Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
+  llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
   Reply(Result ? URI::createFile(*Result).toString() : "");
 }
 
@@ -672,7 +674,7 @@ void ClangdLSPServer::onDocumentHighligh
 }
 
 void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
-                              Callback<Optional<Hover>> Reply) {
+                              Callback<llvm::Optional<Hover>> Reply) {
   Server->findHover(Params.textDocument.uri.file(), Params.position,
                     std::move(Reply));
 }
@@ -719,7 +721,7 @@ void ClangdLSPServer::onSymbolInfo(const
 
 ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
                                  const clangd::CodeCompleteOptions &CCOpts,
-                                 Optional<Path> CompileCommandsDir,
+                                 llvm::Optional<Path> CompileCommandsDir,
                                  bool UseDirBasedCDB,
                                  const ClangdServer::Options &Opts)
     : Transp(Transp), MsgHandler(new MessageHandler(*this)), CCOpts(CCOpts),
@@ -771,7 +773,7 @@ bool ClangdLSPServer::run() {
   return CleanExit && ShutdownRequestReceived;
 }
 
-std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
+std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
                                            const clangd::Diagnostic &D) {
   std::lock_guard<std::mutex> Lock(FixItsMutex);
   auto DiagToFixItsIter = FixItsMap.find(File);
@@ -788,7 +790,7 @@ std::vector<Fix> ClangdLSPServer::getFix
 
 bool ClangdLSPServer::shouldRunCompletion(
     const CompletionParams &Params) const {
-  StringRef Trigger = Params.context.triggerCharacter;
+  llvm::StringRef Trigger = Params.context.triggerCharacter;
   if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
       (Trigger != ">" && Trigger != ":"))
     return true;
@@ -828,7 +830,7 @@ void ClangdLSPServer::onDiagnosticsReady
   DiagnosticToReplacementMap LocalFixIts; // Temporary storage
   for (auto &Diag : Diagnostics) {
     toLSPDiags(Diag, URI, DiagOpts,
-               [&](clangd::Diagnostic Diag, ArrayRef<Fix> Fixes) {
+               [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
                  auto &FixItsForDiagnostic = LocalFixIts[Diag];
                  llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
                  LSPDiagnostics.push_back(std::move(Diag));
@@ -844,7 +846,7 @@ void ClangdLSPServer::onDiagnosticsReady
 
   // Publish diagnostics.
   notify("textDocument/publishDiagnostics",
-         json::Object{
+         llvm::json::Object{
              {"uri", URI},
              {"diagnostics", std::move(LSPDiagnostics)},
          });

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Mon Jan  7 07:45:19 2019
@@ -34,7 +34,6 @@
 #include <future>
 #include <mutex>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -47,7 +46,7 @@ std::string getStandardResourceDir() {
 class RefactoringResultCollector final
     : public tooling::RefactoringResultConsumer {
 public:
-  void handleError(Error Err) override {
+  void handleError(llvm::Error Err) override {
     assert(!Result.hasValue());
     // FIXME: figure out a way to return better message for DiagnosticError.
     // clangd uses llvm::toString to convert the Err to string, however, for
@@ -63,7 +62,7 @@ public:
     Result = std::move(SourceReplacements);
   }
 
-  Optional<Expected<tooling::AtomicChanges>> Result;
+  llvm::Optional<llvm::Expected<tooling::AtomicChanges>> Result;
 };
 
 // Update the FileIndex with new ASTs and plumb the diagnostics responses.
@@ -147,7 +146,7 @@ ClangdServer::ClangdServer(const GlobalC
     AddIndex(DynamicIdx.get());
 }
 
-void ClangdServer::addDocument(PathRef File, StringRef Contents,
+void ClangdServer::addDocument(PathRef File, llvm::StringRef Contents,
                                WantDiagnostics WantDiags) {
   // FIXME: some build systems like Bazel will take time to preparing
   // environment to build the file, it would be nice if we could emit a
@@ -175,13 +174,13 @@ void ClangdServer::codeComplete(PathRef
 
   auto Task = [PCHs, Pos, FS, CodeCompleteOpts,
                this](Path File, Callback<CodeCompleteResult> CB,
-                     Expected<InputsAndPreamble> IP) {
+                     llvm::Expected<InputsAndPreamble> IP) {
     if (!IP)
       return CB(IP.takeError());
     if (isCancelled())
-      return CB(make_error<CancelledError>());
+      return CB(llvm::make_error<CancelledError>());
 
-    Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
+    llvm::Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
     if (CodeCompleteOpts.Index && CodeCompleteOpts.SpeculativeIndexRequest) {
       SpecFuzzyFind.emplace();
       {
@@ -222,7 +221,7 @@ void ClangdServer::signatureHelp(PathRef
   auto FS = FSProvider.getFileSystem();
   auto *Index = this->Index;
   auto Action = [Pos, FS, PCHs, Index](Path File, Callback<SignatureHelp> CB,
-                                       Expected<InputsAndPreamble> IP) {
+                                       llvm::Expected<InputsAndPreamble> IP) {
     if (!IP)
       return CB(IP.takeError());
 
@@ -239,43 +238,44 @@ void ClangdServer::signatureHelp(PathRef
                                 Bind(Action, File.str(), std::move(CB)));
 }
 
-Expected<tooling::Replacements>
-ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
-  Expected<size_t> Begin = positionToOffset(Code, Rng.start);
+llvm::Expected<tooling::Replacements>
+ClangdServer::formatRange(llvm::StringRef Code, PathRef File, Range Rng) {
+  llvm::Expected<size_t> Begin = positionToOffset(Code, Rng.start);
   if (!Begin)
     return Begin.takeError();
-  Expected<size_t> End = positionToOffset(Code, Rng.end);
+  llvm::Expected<size_t> End = positionToOffset(Code, Rng.end);
   if (!End)
     return End.takeError();
   return formatCode(Code, File, {tooling::Range(*Begin, *End - *Begin)});
 }
 
-Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
-                                                         PathRef File) {
+llvm::Expected<tooling::Replacements>
+ClangdServer::formatFile(llvm::StringRef Code, PathRef File) {
   // Format everything.
   return formatCode(Code, File, {tooling::Range(0, Code.size())});
 }
 
-Expected<tooling::Replacements>
-ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
+llvm::Expected<tooling::Replacements>
+ClangdServer::formatOnType(llvm::StringRef Code, PathRef File, Position Pos) {
   // Look for the previous opening brace from the character position and
   // format starting from there.
-  Expected<size_t> CursorPos = positionToOffset(Code, Pos);
+  llvm::Expected<size_t> CursorPos = positionToOffset(Code, Pos);
   if (!CursorPos)
     return CursorPos.takeError();
-  size_t PreviousLBracePos = StringRef(Code).find_last_of('{', *CursorPos);
-  if (PreviousLBracePos == StringRef::npos)
+  size_t PreviousLBracePos =
+      llvm::StringRef(Code).find_last_of('{', *CursorPos);
+  if (PreviousLBracePos == llvm::StringRef::npos)
     PreviousLBracePos = *CursorPos;
   size_t Len = *CursorPos - PreviousLBracePos;
 
   return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
 }
 
-void ClangdServer::rename(PathRef File, Position Pos, StringRef NewName,
+void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
                           Callback<std::vector<tooling::Replacement>> CB) {
   auto Action = [Pos](Path File, std::string NewName,
                       Callback<std::vector<tooling::Replacement>> CB,
-                      Expected<InputsAndAST> InpAST) {
+                      llvm::Expected<InputsAndAST> InpAST) {
     if (!InpAST)
       return CB(InpAST.takeError());
     auto &AST = InpAST->AST;
@@ -323,15 +323,16 @@ void ClangdServer::rename(PathRef File,
 }
 
 void ClangdServer::dumpAST(PathRef File,
-                           unique_function<void(std::string)> Callback) {
-  auto Action = [](decltype(Callback) Callback, Expected<InputsAndAST> InpAST) {
+                           llvm::unique_function<void(std::string)> Callback) {
+  auto Action = [](decltype(Callback) Callback,
+                   llvm::Expected<InputsAndAST> InpAST) {
     if (!InpAST) {
       llvm::consumeError(InpAST.takeError());
       return Callback("<no-ast>");
     }
     std::string Result;
 
-    raw_string_ostream ResultOS(Result);
+    llvm::raw_string_ostream ResultOS(Result);
     clangd::dumpAST(InpAST->AST, ResultOS);
     ResultOS.flush();
 
@@ -344,7 +345,7 @@ void ClangdServer::dumpAST(PathRef File,
 void ClangdServer::findDefinitions(PathRef File, Position Pos,
                                    Callback<std::vector<Location>> CB) {
   auto Action = [Pos, this](Callback<std::vector<Location>> CB,
-                            Expected<InputsAndAST> InpAST) {
+                            llvm::Expected<InputsAndAST> InpAST) {
     if (!InpAST)
       return CB(InpAST.takeError());
     CB(clangd::findDefinitions(InpAST->AST, Pos, Index));
@@ -353,13 +354,13 @@ void ClangdServer::findDefinitions(PathR
   WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
 }
 
-Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
+llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
 
-  StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
-                                  ".c++", ".m", ".mm"};
-  StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
+  llvm::StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
+                                        ".c++", ".m", ".mm"};
+  llvm::StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
 
-  StringRef PathExt = sys::path::extension(Path);
+  llvm::StringRef PathExt = llvm::sys::path::extension(Path);
 
   // Lookup in a list of known extensions.
   auto SourceIter =
@@ -381,28 +382,28 @@ Optional<Path> ClangdServer::switchSourc
 
   // Array to lookup extensions for the switch. An opposite of where original
   // extension was found.
-  ArrayRef<StringRef> NewExts;
+  llvm::ArrayRef<llvm::StringRef> NewExts;
   if (IsSource)
     NewExts = HeaderExtensions;
   else
     NewExts = SourceExtensions;
 
   // Storage for the new path.
-  SmallString<128> NewPath = StringRef(Path);
+  llvm::SmallString<128> NewPath = llvm::StringRef(Path);
 
   // Instance of vfs::FileSystem, used for file existence checks.
   auto FS = FSProvider.getFileSystem();
 
   // Loop through switched extension candidates.
-  for (StringRef NewExt : NewExts) {
-    sys::path::replace_extension(NewPath, NewExt);
+  for (llvm::StringRef NewExt : NewExts) {
+    llvm::sys::path::replace_extension(NewPath, NewExt);
     if (FS->exists(NewPath))
       return NewPath.str().str(); // First str() to convert from SmallString to
                                   // StringRef, second to convert from StringRef
                                   // to std::string
 
     // Also check NewExt in upper-case, just in case.
-    sys::path::replace_extension(NewPath, NewExt.upper());
+    llvm::sys::path::replace_extension(NewPath, NewExt.upper());
     if (FS->exists(NewPath))
       return NewPath.str().str();
   }
@@ -410,9 +411,9 @@ Optional<Path> ClangdServer::switchSourc
   return None;
 }
 
-Expected<tooling::Replacements>
-ClangdServer::formatCode(StringRef Code, PathRef File,
-                         ArrayRef<tooling::Range> Ranges) {
+llvm::Expected<tooling::Replacements>
+ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
+                         llvm::ArrayRef<tooling::Range> Ranges) {
   // Call clang-format.
   auto FS = FSProvider.getFileSystem();
   auto Style = format::getStyle(format::DefaultFormatStyle, File,
@@ -435,7 +436,7 @@ ClangdServer::formatCode(StringRef Code,
 void ClangdServer::findDocumentHighlights(
     PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
   auto Action = [Pos](Callback<std::vector<DocumentHighlight>> CB,
-                      Expected<InputsAndAST> InpAST) {
+                      llvm::Expected<InputsAndAST> InpAST) {
     if (!InpAST)
       return CB(InpAST.takeError());
     CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
@@ -445,9 +446,9 @@ void ClangdServer::findDocumentHighlight
 }
 
 void ClangdServer::findHover(PathRef File, Position Pos,
-                             Callback<Optional<Hover>> CB) {
-  auto Action = [Pos](Callback<Optional<Hover>> CB,
-                      Expected<InputsAndAST> InpAST) {
+                             Callback<llvm::Optional<Hover>> CB) {
+  auto Action = [Pos](Callback<llvm::Optional<Hover>> CB,
+                      llvm::Expected<InputsAndAST> InpAST) {
     if (!InpAST)
       return CB(InpAST.takeError());
     CB(clangd::getHover(InpAST->AST, Pos));
@@ -458,7 +459,7 @@ void ClangdServer::findHover(PathRef Fil
 
 tooling::CompileCommand ClangdServer::getCompileCommand(PathRef File) {
   trace::Span Span("GetCompileCommand");
-  Optional<tooling::CompileCommand> C = CDB.getCompileCommand(File);
+  llvm::Optional<tooling::CompileCommand> C = CDB.getCompileCommand(File);
   if (!C) // FIXME: Suppress diagnostics? Let the user know?
     C = CDB.getFallbackCommand(File);
 
@@ -474,7 +475,8 @@ void ClangdServer::onFileEvent(const Did
 }
 
 void ClangdServer::workspaceSymbols(
-    StringRef Query, int Limit, Callback<std::vector<SymbolInformation>> CB) {
+    llvm::StringRef Query, int Limit,
+    Callback<std::vector<SymbolInformation>> CB) {
   std::string QueryCopy = Query;
   WorkScheduler.run(
       "getWorkspaceSymbols",
@@ -486,7 +488,7 @@ void ClangdServer::workspaceSymbols(
           std::move(CB)));
 }
 
-void ClangdServer::documentSymbols(StringRef File,
+void ClangdServer::documentSymbols(llvm::StringRef File,
                                    Callback<std::vector<DocumentSymbol>> CB) {
   auto Action = [](Callback<std::vector<DocumentSymbol>> CB,
                    llvm::Expected<InputsAndAST> InpAST) {
@@ -501,7 +503,7 @@ void ClangdServer::documentSymbols(Strin
 void ClangdServer::findReferences(PathRef File, Position Pos,
                                   Callback<std::vector<Location>> CB) {
   auto Action = [Pos, this](Callback<std::vector<Location>> CB,
-                            Expected<InputsAndAST> InpAST) {
+                            llvm::Expected<InputsAndAST> InpAST) {
     if (!InpAST)
       return CB(InpAST.takeError());
     CB(clangd::findReferences(InpAST->AST, Pos, Index));
@@ -513,7 +515,7 @@ void ClangdServer::findReferences(PathRe
 void ClangdServer::symbolInfo(PathRef File, Position Pos,
                               Callback<std::vector<SymbolDetails>> CB) {
   auto Action = [Pos](Callback<std::vector<SymbolDetails>> CB,
-                      Expected<InputsAndAST> InpAST) {
+                      llvm::Expected<InputsAndAST> InpAST) {
     if (!InpAST)
       return CB(InpAST.takeError());
     CB(clangd::getSymbolInfo(InpAST->AST, Pos));
@@ -528,7 +530,7 @@ ClangdServer::getUsedBytesPerFile() cons
 }
 
 LLVM_NODISCARD bool
-ClangdServer::blockUntilIdleForTest(Optional<double> TimeoutSeconds) {
+ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
   return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds)) &&
          (!BackgroundIdx ||
           BackgroundIdx->blockUntilIdleForTest(TimeoutSeconds));

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Mon Jan  7 07:45:19 2019
@@ -36,7 +36,6 @@
 #include "llvm/Support/raw_ostream.h"
 #include <algorithm>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -45,7 +44,7 @@ bool compileCommandsAreEqual(const tooli
                              const tooling::CompileCommand &RHS) {
   // We don't check for Output, it should not matter to clangd.
   return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
-         makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
+         llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
 }
 
 template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
@@ -80,8 +79,8 @@ public:
   std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
 
 protected:
-  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
-                                                 StringRef InFile) override {
+  std::unique_ptr<ASTConsumer>
+  CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
     return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
   }
 
@@ -179,12 +178,12 @@ private:
       if (Inc.Resolved != "")
         File = SM.getFileManager().getFile(Inc.Resolved);
 
-      StringRef WrittenFilename =
-          StringRef(Inc.Written).drop_front().drop_back();
-      bool Angled = StringRef(Inc.Written).startswith("<");
+      llvm::StringRef WrittenFilename =
+          llvm::StringRef(Inc.Written).drop_front().drop_back();
+      bool Angled = llvm::StringRef(Inc.Written).startswith("<");
 
       // Re-lex the #include directive to find its interesting parts.
-      StringRef Src = SM.getBufferData(SM.getMainFileID());
+      llvm::StringRef Src = SM.getBufferData(SM.getMainFileID());
       Lexer RawLexer(SM.getLocForStartOfFile(SM.getMainFileID()), LangOpts,
                      Src.begin(), Src.begin() + Inc.HashOffset, Src.end());
       Token HashTok, IncludeTok, FilenameTok;
@@ -205,7 +204,7 @@ private:
       if (File)
         Delegate->FileSkipped(*File, FilenameTok, Inc.FileKind);
       else {
-        SmallString<1> UnusedRecovery;
+        llvm::SmallString<1> UnusedRecovery;
         Delegate->FileNotFound(WrittenFilename, UnusedRecovery);
       }
     }
@@ -220,16 +219,16 @@ private:
 
 } // namespace
 
-void dumpAST(ParsedAST &AST, raw_ostream &OS) {
+void dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
   AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
 }
 
-Optional<ParsedAST>
+llvm::Optional<ParsedAST>
 ParsedAST::build(std::unique_ptr<CompilerInvocation> CI,
                  std::shared_ptr<const PreambleData> Preamble,
-                 std::unique_ptr<MemoryBuffer> Buffer,
+                 std::unique_ptr<llvm::MemoryBuffer> Buffer,
                  std::shared_ptr<PCHContainerOperations> PCHs,
-                 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
+                 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
   assert(CI);
   // Command-line parsing sets DisableFree to true by default, but we don't want
   // to leak memory in clangd.
@@ -362,7 +361,7 @@ const Preprocessor &ParsedAST::getPrepro
   return Clang->getPreprocessor();
 }
 
-ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
+llvm::ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
   return LocalTopLevelDecls;
 }
 
@@ -438,7 +437,7 @@ buildCompilerInvocation(const ParseInput
   // FIXME(ibiryukov): store diagnostics from CommandLine when we start
   // reporting them.
   IgnoreDiagnostics IgnoreDiagnostics;
-  IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
+  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
       CompilerInstance::createDiagnostics(new DiagnosticOptions,
                                           &IgnoreDiagnostics, false);
   std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
@@ -460,7 +459,7 @@ buildPreamble(PathRef FileName, Compiler
               PreambleParsedCallback PreambleCallback) {
   // Note that we don't need to copy the input contents, preamble can live
   // without those.
-  auto ContentsBuffer = MemoryBuffer::getMemBuffer(Inputs.Contents);
+  auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Inputs.Contents);
   auto Bounds =
       ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
 
@@ -468,7 +467,7 @@ buildPreamble(PathRef FileName, Compiler
       compileCommandsAreEqual(Inputs.CompileCommand, OldCompileCommand) &&
       OldPreamble->Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
                                      Inputs.FS.get())) {
-    vlog("Reusing preamble for file {0}", Twine(FileName));
+    vlog("Reusing preamble for file {0}", llvm::Twine(FileName));
     return OldPreamble;
   }
   vlog("Preamble for file {0} cannot be reused. Attempting to rebuild it.",
@@ -477,7 +476,7 @@ buildPreamble(PathRef FileName, Compiler
   trace::Span Tracer("BuildPreamble");
   SPAN_ATTACH(Tracer, "File", FileName);
   StoreDiags PreambleDiagnostics;
-  IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
+  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
       CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
                                           &PreambleDiagnostics, false);
 
@@ -496,7 +495,7 @@ buildPreamble(PathRef FileName, Compiler
     // dirs.
   }
 
-  SmallString<32> AbsFileName(FileName);
+  llvm::SmallString<32> AbsFileName(FileName);
   Inputs.FS->makeAbsolute(AbsFileName);
   auto StatCache = llvm::make_unique<PreambleFileStatusCache>(AbsFileName);
   auto BuiltPreamble = PrecompiledPreamble::Build(
@@ -520,11 +519,11 @@ buildPreamble(PathRef FileName, Compiler
   }
 }
 
-Optional<ParsedAST> buildAST(PathRef FileName,
-                             std::unique_ptr<CompilerInvocation> Invocation,
-                             const ParseInputs &Inputs,
-                             std::shared_ptr<const PreambleData> Preamble,
-                             std::shared_ptr<PCHContainerOperations> PCHs) {
+llvm::Optional<ParsedAST>
+buildAST(PathRef FileName, std::unique_ptr<CompilerInvocation> Invocation,
+         const ParseInputs &Inputs,
+         std::shared_ptr<const PreambleData> Preamble,
+         std::shared_ptr<PCHContainerOperations> PCHs) {
   trace::Span Tracer("BuildAST");
   SPAN_ATTACH(Tracer, "File", FileName);
 
@@ -537,9 +536,10 @@ Optional<ParsedAST> buildAST(PathRef Fil
     // 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,

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Mon Jan  7 07:45:19 2019
@@ -59,7 +59,6 @@
 // We log detailed candidate here if you run with -debug-only=codecomplete.
 #define DEBUG_TYPE "CodeComplete"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -181,7 +180,8 @@ std::string getOptionalParameters(const
 
 /// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
 /// include.
-static Expected<HeaderFile> toHeaderFile(StringRef Header, StringRef HintPath) {
+static llvm::Expected<HeaderFile> toHeaderFile(llvm::StringRef Header,
+                                               llvm::StringRef HintPath) {
   if (isLiteralInclude(Header))
     return HeaderFile{Header.str(), /*Verbatim=*/true};
   auto U = URI::parse(Header);
@@ -203,16 +203,16 @@ static Expected<HeaderFile> toHeaderFile
 /// A code completion result, in clang-native form.
 /// It may be promoted to a CompletionItem if it's among the top-ranked results.
 struct CompletionCandidate {
-  StringRef Name; // Used for filtering and sorting.
+  llvm::StringRef Name; // Used for filtering and sorting.
   // We may have a result from Sema, from the index, or both.
   const CodeCompletionResult *SemaResult = nullptr;
   const Symbol *IndexResult = nullptr;
-  SmallVector<StringRef, 1> RankedIncludeHeaders;
+  llvm::SmallVector<llvm::StringRef, 1> RankedIncludeHeaders;
 
   // Returns a token identifying the overload set this is part of.
   // 0 indicates it's not part of any overload set.
   size_t overloadSet() const {
-    SmallString<256> Scratch;
+    llvm::SmallString<256> Scratch;
     if (IndexResult) {
       switch (IndexResult->SymInfo.Kind) {
       case index::SymbolKind::ClassMethod:
@@ -226,7 +226,7 @@ struct CompletionCandidate {
       case index::SymbolKind::Function:
         // We can't group overloads together that need different #includes.
         // This could break #include insertion.
-        return hash_combine(
+        return llvm::hash_combine(
             (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
             headerToInsertIfAllowed().getValueOr(""));
       default:
@@ -239,14 +239,15 @@ struct CompletionCandidate {
     if (!D || !D->isFunctionOrFunctionTemplate())
       return 0;
     {
-      raw_svector_ostream OS(Scratch);
+      llvm::raw_svector_ostream OS(Scratch);
       D->printQualifiedName(OS);
     }
-    return hash_combine(Scratch, headerToInsertIfAllowed().getValueOr(""));
+    return llvm::hash_combine(Scratch,
+                              headerToInsertIfAllowed().getValueOr(""));
   }
 
   // The best header to include if include insertion is allowed.
-  Optional<StringRef> headerToInsertIfAllowed() const {
+  llvm::Optional<llvm::StringRef> headerToInsertIfAllowed() const {
     if (RankedIncludeHeaders.empty())
       return None;
     if (SemaResult && SemaResult->Declaration) {
@@ -260,7 +261,7 @@ struct CompletionCandidate {
     return RankedIncludeHeaders[0];
   }
 
-  using Bundle = SmallVector<CompletionCandidate, 4>;
+  using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
 };
 using ScoredBundle =
     std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
@@ -283,8 +284,9 @@ struct ScoredBundleGreater {
 struct CodeCompletionBuilder {
   CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
                         CodeCompletionString *SemaCCS,
-                        ArrayRef<std::string> QueryScopes,
-                        const IncludeInserter &Includes, StringRef FileName,
+                        llvm::ArrayRef<std::string> QueryScopes,
+                        const IncludeInserter &Includes,
+                        llvm::StringRef FileName,
                         CodeCompletionContext::Kind ContextKind,
                         const CodeCompleteOptions &Opts)
       : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments),
@@ -292,7 +294,7 @@ struct CodeCompletionBuilder {
     add(C, SemaCCS);
     if (C.SemaResult) {
       Completion.Origin |= SymbolOrigin::AST;
-      Completion.Name = StringRef(SemaCCS->getTypedText());
+      Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
       if (Completion.Scope.empty()) {
         if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
             (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
@@ -330,9 +332,9 @@ struct CodeCompletionBuilder {
       // If the completion was visible to Sema, no qualifier is needed. This
       // avoids unneeded qualifiers in cases like with `using ns::X`.
       if (Completion.RequiredQualifier.empty() && !C.SemaResult) {
-        StringRef ShortestQualifier = C.IndexResult->Scope;
-        for (StringRef Scope : QueryScopes) {
-          StringRef Qualifier = C.IndexResult->Scope;
+        llvm::StringRef ShortestQualifier = C.IndexResult->Scope;
+        for (llvm::StringRef Scope : QueryScopes) {
+          llvm::StringRef Qualifier = C.IndexResult->Scope;
           if (Qualifier.consume_front(Scope) &&
               Qualifier.size() < ShortestQualifier.size())
             ShortestQualifier = Qualifier;
@@ -343,8 +345,8 @@ struct CodeCompletionBuilder {
     }
 
     // Turn absolute path into a literal string that can be #included.
-    auto Inserted =
-        [&](StringRef Header) -> Expected<std::pair<std::string, bool>> {
+    auto Inserted = [&](llvm::StringRef Header)
+        -> llvm::Expected<std::pair<std::string, bool>> {
       auto ResolvedDeclaring =
           toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
       if (!ResolvedDeclaring)
@@ -462,7 +464,7 @@ private:
       //   foo<${1:class}>(${2:int p1}).
       //   We transform this pattern to '<$1>()$0' or '<$0>()'.
 
-      bool EmptyArgs = StringRef(*Snippet).endswith("()");
+      bool EmptyArgs = llvm::StringRef(*Snippet).endswith("()");
       if (Snippet->front() == '<')
         return EmptyArgs ? "<$1>()$0" : "<$1>($0)";
       if (Snippet->front() == '(')
@@ -476,7 +478,7 @@ private:
 
       // Classes and template using aliases can only have template arguments,
       // e.g. Foo<${1:class}>.
-      if (StringRef(*Snippet).endswith("<>"))
+      if (llvm::StringRef(*Snippet).endswith("<>"))
         return "<>"; // can happen with defaulted template arguments.
       return "<$0>";
     }
@@ -492,14 +494,14 @@ private:
 
   ASTContext &ASTCtx;
   CodeCompletion Completion;
-  SmallVector<BundledEntry, 1> Bundled;
+  llvm::SmallVector<BundledEntry, 1> Bundled;
   bool ExtractDocumentation;
   bool EnableFunctionArgSnippets;
 };
 
 // Determine the symbol ID for a Sema code completion result, if possible.
-Optional<SymbolID> getSymbolID(const CodeCompletionResult &R,
-                               const SourceManager &SM) {
+llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R,
+                                     const SourceManager &SM) {
   switch (R.Kind) {
   case CodeCompletionResult::RK_Declaration:
   case CodeCompletionResult::RK_Pattern: {
@@ -539,13 +541,13 @@ struct SpecifiedScope {
   std::vector<std::string> AccessibleScopes;
   // The full scope qualifier as typed by the user (without the leading "::").
   // Set if the qualifier is not fully resolved by Sema.
-  Optional<std::string> UnresolvedQualifier;
+  llvm::Optional<std::string> UnresolvedQualifier;
 
   // Construct scopes being queried in indexes. The results are deduplicated.
   // This method format the scopes to match the index request representation.
   std::vector<std::string> scopesForIndexQuery() {
     std::set<std::string> Results;
-    for (StringRef AS : AccessibleScopes)
+    for (llvm::StringRef AS : AccessibleScopes)
       Results.insert(
           ((UnresolvedQualifier ? *UnresolvedQualifier : "") + AS).str());
     return {Results.begin(), Results.end()};
@@ -688,7 +690,7 @@ static bool isBlacklistedMember(const Na
 // within the callback.
 struct CompletionRecorder : public CodeCompleteConsumer {
   CompletionRecorder(const CodeCompleteOptions &Opts,
-                     unique_function<void()> ResultsCallback)
+                     llvm::unique_function<void()> ResultsCallback)
       : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
                              /*OutputIsBinary=*/false),
         CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
@@ -766,7 +768,7 @@ struct CompletionRecorder : public CodeC
 
   // Returns the filtering/sorting name for Result, which must be from Results.
   // Returned string is owned by this recorder (or the AST).
-  StringRef getName(const CodeCompletionResult &Result) {
+  llvm::StringRef getName(const CodeCompletionResult &Result) {
     switch (Result.Kind) {
     case CodeCompletionResult::RK_Declaration:
       if (auto *ID = Result.Declaration->getIdentifier())
@@ -796,13 +798,13 @@ private:
   CodeCompleteOptions Opts;
   std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
   CodeCompletionTUInfo CCTUInfo;
-  unique_function<void()> ResultsCallback;
+  llvm::unique_function<void()> ResultsCallback;
 };
 
 struct ScoredSignature {
   // When set, requires documentation to be requested from the index with this
   // ID.
-  Optional<SymbolID> IDForDoc;
+  llvm::Optional<SymbolID> IDForDoc;
   SignatureInformation Signature;
   SignatureQualitySignals Quality;
 };
@@ -862,7 +864,7 @@ public:
 
     // Sema does not load the docs from the preamble, so we need to fetch extra
     // docs from the index instead.
-    DenseMap<SymbolID, std::string> FetchedDocs;
+    llvm::DenseMap<SymbolID, std::string> FetchedDocs;
     if (Index) {
       LookupRequest IndexRequest;
       for (const auto &S : ScoredSignatures) {
@@ -930,7 +932,7 @@ private:
   // CompletionString.h.
   ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
                                            const CodeCompletionString &CCS,
-                                           StringRef DocComment) const {
+                                           llvm::StringRef DocComment) const {
     SignatureInformation Signature;
     SignatureQualitySignals Signal;
     const char *ReturnType = nullptr;
@@ -1002,9 +1004,9 @@ struct SemaCompleteInput {
   PathRef FileName;
   const tooling::CompileCommand &Command;
   const PreambleData *Preamble;
-  StringRef Contents;
+  llvm::StringRef Contents;
   Position Pos;
-  IntrusiveRefCntPtr<vfs::FileSystem> VFS;
+  llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
   std::shared_ptr<PCHContainerOperations> PCHs;
 };
 
@@ -1025,7 +1027,7 @@ bool semaCodeComplete(std::unique_ptr<Co
     // working dirs.
   }
 
-  IntrusiveRefCntPtr<vfs::FileSystem> VFS = Input.VFS;
+  llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = Input.VFS;
   if (Input.Preamble && Input.Preamble->StatCache)
     VFS = Input.Preamble->StatCache->getConsumingFS(std::move(VFS));
   IgnoreDiagnostics DummyDiagsConsumer;
@@ -1056,8 +1058,8 @@ bool semaCodeComplete(std::unique_ptr<Co
            FrontendOpts.CodeCompletionAt.Column) =
       offsetToClangLineColumn(Input.Contents, *Offset);
 
-  std::unique_ptr<MemoryBuffer> ContentsBuffer =
-      MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
+  std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
+      llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
   // The diagnostic options must be set before creating a CompilerInstance.
   CI->getDiagnosticOpts().IgnoreWarnings = true;
   // We reuse the preamble whether it's valid or not. This is a
@@ -1139,8 +1141,10 @@ std::future<SymbolSlab> 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.
-Optional<FuzzyFindRequest> speculativeFuzzyFindRequestForCompletion(
-    FuzzyFindRequest CachedReq, PathRef File, StringRef Content, Position Pos) {
+llvm::Optional<FuzzyFindRequest>
+speculativeFuzzyFindRequestForCompletion(FuzzyFindRequest CachedReq,
+                                         PathRef File, llvm::StringRef Content,
+                                         Position Pos) {
   auto Filter = speculateCompletionFilter(Content, Pos);
   if (!Filter) {
     elog("Failed to speculate filter text for code completion at Pos "
@@ -1155,7 +1159,7 @@ Optional<FuzzyFindRequest> speculativeFu
 // Returns the most popular include header for \p Sym. If two headers are
 // equally popular, prefer the shorter one. Returns empty string if \p Sym has
 // no include header.
-SmallVector<StringRef, 1> getRankedIncludes(const Symbol &Sym) {
+llvm::SmallVector<llvm::StringRef, 1> getRankedIncludes(const Symbol &Sym) {
   auto Includes = Sym.IncludeHeaders;
   // Sort in descending order by reference count and header length.
   llvm::sort(Includes, [](const Symbol::IncludeHeaderWithReferences &LHS,
@@ -1164,7 +1168,7 @@ SmallVector<StringRef, 1> getRankedInclu
       return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
     return LHS.References > RHS.References;
   });
-  SmallVector<StringRef, 1> Headers;
+  llvm::SmallVector<llvm::StringRef, 1> Headers;
   for (const auto &Include : Includes)
     Headers.push_back(Include.IncludeHeader);
   return Headers;
@@ -1209,22 +1213,22 @@ class CodeCompleteFlow {
   CompletionRecorder *Recorder = nullptr;
   int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
   bool Incomplete = false;       // Would more be available with a higher limit?
-  Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
+  llvm::Optional<FuzzyMatcher> Filter;  // Initialized once Sema runs.
   std::vector<std::string> QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
-  Optional<ScopeDistance> ScopeProximity;
+  llvm::Optional<ScopeDistance> ScopeProximity;
   llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
   // This is available after Sema has run.
-  Optional<IncludeInserter> Inserter;  // Available during runWithSema.
-  Optional<URIDistance> FileProximity; // Initialized once Sema runs.
+  llvm::Optional<IncludeInserter> Inserter;  // Available during runWithSema.
+  llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
   /// Speculative request based on the cached request and the filter text before
   /// the cursor.
   /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
   /// set and contains a cached request.
-  Optional<FuzzyFindRequest> SpecReq;
+  llvm::Optional<FuzzyFindRequest> SpecReq;
 
 public:
   // A CodeCompleteFlow object is only useful for calling run() exactly once.
@@ -1274,7 +1278,7 @@ public:
       // The per-result proximity scoring is (amortized) very cheap.
       FileDistanceOptions ProxOpts{}; // Use defaults.
       const auto &SM = Recorder->CCSema->getSourceManager();
-      StringMap<SourceParams> ProxSources;
+      llvm::StringMap<SourceParams> ProxSources;
       for (auto &Entry : Includes.includeDepth(
                SM.getFileEntryForID(SM.getMainFileID())->getName())) {
         auto &Source = ProxSources[Entry.getKey()];
@@ -1294,7 +1298,7 @@ public:
       log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
           "expected type {3}",
           getCompletionKindString(Recorder->CCContext.getKind()),
-          join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+          llvm::join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
           PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
                         : "<none>");
     });
@@ -1419,7 +1423,7 @@ private:
                const SymbolSlab &IndexResults) {
     trace::Span Tracer("Merge and score results");
     std::vector<CompletionCandidate::Bundle> Bundles;
-    DenseMap<size_t, size_t> BundleLookup;
+    llvm::DenseMap<size_t, size_t> BundleLookup;
     auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
                             const Symbol *IndexResult) {
       CompletionCandidate C;
@@ -1438,7 +1442,7 @@ private:
         Bundles.back().push_back(std::move(C));
       }
     };
-    DenseSet<const Symbol *> UsedIndexResults;
+    llvm::DenseSet<const Symbol *> UsedIndexResults;
     auto CorrespondingIndexResult =
         [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
       if (auto SymID =
@@ -1468,7 +1472,7 @@ private:
     return std::move(Top).items();
   }
 
-  Optional<float> fuzzyScore(const CompletionCandidate &C) {
+  llvm::Optional<float> fuzzyScore(const CompletionCandidate &C) {
     // Macros can be very spammy, so we only support prefix completion.
     // We won't end up with underfull index results, as macros are sema-only.
     if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
@@ -1535,8 +1539,8 @@ private:
                                : Scores.Quality;
 
     dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
-         to_string(Origin), Scores.Total, to_string(Quality),
-         to_string(Relevance));
+         llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
+         llvm::to_string(Relevance));
 
     NSema += bool(Origin & SymbolOrigin::AST);
     NIndex += FromIndex;
@@ -1546,7 +1550,7 @@ private:
   }
 
   CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
-    Optional<CodeCompletionBuilder> Builder;
+    llvm::Optional<CodeCompletionBuilder> Builder;
     for (const auto &Item : Bundle) {
       CodeCompletionString *SemaCCS =
           Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
@@ -1584,12 +1588,13 @@ clang::CodeCompleteOptions CodeCompleteO
   return Result;
 }
 
-Expected<StringRef> speculateCompletionFilter(StringRef Content, Position Pos) {
+llvm::Expected<llvm::StringRef>
+speculateCompletionFilter(llvm::StringRef Content, Position Pos) {
   auto Offset = positionToOffset(Content, Pos);
   if (!Offset)
-    return make_error<StringError>(
+    return llvm::make_error<llvm::StringError>(
         "Failed to convert position to offset in content.",
-        inconvertibleErrorCode());
+        llvm::inconvertibleErrorCode());
   if (*Offset == 0)
     return "";
 
@@ -1610,8 +1615,8 @@ Expected<StringRef> speculateCompletionF
 
 CodeCompleteResult
 codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
-             const PreambleData *Preamble, StringRef Contents, Position Pos,
-             IntrusiveRefCntPtr<vfs::FileSystem> VFS,
+             const PreambleData *Preamble, llvm::StringRef Contents,
+             Position Pos, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
              std::shared_ptr<PCHContainerOperations> PCHs,
              CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind) {
   return CodeCompleteFlow(FileName,
@@ -1622,9 +1627,9 @@ codeComplete(PathRef FileName, const too
 
 SignatureHelp signatureHelp(PathRef FileName,
                             const tooling::CompileCommand &Command,
-                            const PreambleData *Preamble, StringRef Contents,
-                            Position Pos,
-                            IntrusiveRefCntPtr<vfs::FileSystem> VFS,
+                            const PreambleData *Preamble,
+                            llvm::StringRef Contents, Position Pos,
+                            llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
                             std::shared_ptr<PCHContainerOperations> PCHs,
                             const SymbolIndex *Index) {
   SignatureHelp Result;
@@ -1669,12 +1674,12 @@ CompletionItem CodeCompletion::render(co
   LSP.label = ((InsertInclude && InsertInclude->Insertion)
                    ? Opts.IncludeIndicator.Insert
                    : Opts.IncludeIndicator.NoInsert) +
-              (Opts.ShowOrigins ? "[" + to_string(Origin) + "]" : "") +
+              (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
               RequiredQualifier + Name + Signature;
 
   LSP.kind = Kind;
-  LSP.detail =
-      BundleSize > 1 ? formatv("[{0} overloads]", BundleSize) : ReturnType;
+  LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
+                              : ReturnType;
   LSP.deprecated = Deprecated;
   if (InsertInclude)
     LSP.detail += "\n" + InsertInclude->Header;
@@ -1711,12 +1716,13 @@ CompletionItem CodeCompletion::render(co
   return LSP;
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CodeCompletion &C) {
   // For now just lean on CompletionItem.
   return OS << C.render(CodeCompleteOptions());
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+                              const CodeCompleteResult &R) {
   OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
      << " (" << getCompletionKindString(R.Context) << ")"
      << " items:\n";

Modified: clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp Mon Jan  7 07:45:19 2019
@@ -14,17 +14,16 @@
 #include "clang/Basic/SourceManager.h"
 #include <utility>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
 
 bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
   return Chunk.Kind == CodeCompletionString::CK_Informative &&
-         StringRef(Chunk.Text).endswith("::");
+         llvm::StringRef(Chunk.Text).endswith("::");
 }
 
-void appendEscapeSnippet(const StringRef Text, std::string *Out) {
+void appendEscapeSnippet(const llvm::StringRef Text, std::string *Out) {
   for (const auto Character : Text) {
     if (Character == '$' || Character == '}' || Character == '\\')
       Out->push_back('\\');
@@ -32,13 +31,13 @@ void appendEscapeSnippet(const StringRef
   }
 }
 
-bool looksLikeDocComment(StringRef CommentText) {
+bool looksLikeDocComment(llvm::StringRef CommentText) {
   // We don't report comments that only contain "special" chars.
   // This avoids reporting various delimiters, like:
   //   =================
   //   -----------------
   //   *****************
-  return CommentText.find_first_not_of("/*-= \t\r\n") != StringRef::npos;
+  return CommentText.find_first_not_of("/*-= \t\r\n") != llvm::StringRef::npos;
 }
 
 } // namespace
@@ -97,7 +96,7 @@ void getSignature(const CodeCompletionSt
       //   treat them carefully. For Objective-C methods, all typed-text chunks
       //   will end in ':' (unless there are no arguments, in which case we
       //   can safely treat them as C++).
-      if (!StringRef(Chunk.Text).endswith(":")) { // Treat as C++.
+      if (!llvm::StringRef(Chunk.Text).endswith(":")) { // Treat as C++.
         if (RequiredQualifiers)
           *RequiredQualifiers = std::move(*Signature);
         Signature->clear();
@@ -171,7 +170,7 @@ void getSignature(const CodeCompletionSt
 }
 
 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;

Modified: clang-tools-extra/trunk/clangd/Compiler.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Compiler.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Compiler.cpp (original)
+++ clang-tools-extra/trunk/clangd/Compiler.cpp Mon Jan  7 07:45:19 2019
@@ -14,21 +14,20 @@
 #include "llvm/Support/Format.h"
 #include "llvm/Support/FormatVariadic.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
 void IgnoreDiagnostics::log(DiagnosticsEngine::Level DiagLevel,
                             const clang::Diagnostic &Info) {
   // FIXME: format lazily, in case vlog is off.
-  SmallString<64> Message;
+  llvm::SmallString<64> Message;
   Info.FormatDiagnostic(Message);
 
-  SmallString<64> Location;
+  llvm::SmallString<64> Location;
   if (Info.hasSourceManager() && Info.getLocation().isValid()) {
     auto &SourceMgr = Info.getSourceManager();
     auto Loc = SourceMgr.getFileLoc(Info.getLocation());
-    raw_svector_ostream OS(Location);
+    llvm::raw_svector_ostream OS(Location);
     Loc.print(OS, SourceMgr);
     OS << ":";
   }
@@ -41,11 +40,13 @@ void IgnoreDiagnostics::HandleDiagnostic
   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 "

Modified: clang-tools-extra/trunk/clangd/Diagnostics.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Diagnostics.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Diagnostics.cpp (original)
+++ clang-tools-extra/trunk/clangd/Diagnostics.cpp Mon Jan  7 07:45:19 2019
@@ -17,7 +17,6 @@
 #include "llvm/Support/Path.h"
 #include <algorithm>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -57,7 +56,7 @@ Range diagnosticRange(const clang::Diagn
     if (locationInRange(Loc, R, M))
       return halfOpenToRange(M, R);
   }
-  Optional<Range> FallbackRange;
+  llvm::Optional<Range> FallbackRange;
   // The range may be given as a fixit hint instead.
   for (const auto &F : D.getFixItHints()) {
     auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
@@ -93,7 +92,7 @@ bool isNote(DiagnosticsEngine::Level L)
   return L == DiagnosticsEngine::Note || L == DiagnosticsEngine::Remark;
 }
 
-StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
+llvm::StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
   switch (Lvl) {
   case DiagnosticsEngine::Ignored:
     return "ignored";
@@ -122,12 +121,12 @@ StringRef diagLeveltoString(DiagnosticsE
 ///
 ///     dir1/dir2/dir3/../../dir4/header.h:12:23
 ///     error: undeclared identifier
-void printDiag(raw_string_ostream &OS, const DiagBase &D) {
+void printDiag(llvm::raw_string_ostream &OS, const DiagBase &D) {
   if (D.InsideMainFile) {
     // Paths to main files are often taken from compile_command.json, where they
     // are typically absolute. To reduce noise we print only basename for them,
     // it should not be confusing and saves space.
-    OS << sys::path::filename(D.File) << ":";
+    OS << llvm::sys::path::filename(D.File) << ":";
   } else {
     OS << D.File << ":";
   }
@@ -147,7 +146,7 @@ void printDiag(raw_string_ostream &OS, c
 /// Capitalizes the first word in the diagnostic's message.
 std::string capitalize(std::string Message) {
   if (!Message.empty())
-    Message[0] = toUpper(Message[0]);
+    Message[0] = llvm::toUpper(Message[0]);
   return Message;
 }
 
@@ -165,7 +164,7 @@ std::string capitalize(std::string Messa
 ///     note: candidate function not viable: requires 3 arguments
 std::string mainMessage(const Diag &D) {
   std::string Result;
-  raw_string_ostream OS(Result);
+  llvm::raw_string_ostream OS(Result);
   OS << D.Message;
   for (auto &Note : D.Notes) {
     OS << "\n\n";
@@ -180,7 +179,7 @@ std::string mainMessage(const Diag &D) {
 /// for the user to understand the note.
 std::string noteMessage(const Diag &Main, const DiagBase &Note) {
   std::string Result;
-  raw_string_ostream OS(Result);
+  llvm::raw_string_ostream OS(Result);
   OS << Note.Message;
   OS << "\n\n";
   printDiag(OS, Main);
@@ -189,7 +188,7 @@ std::string noteMessage(const Diag &Main
 }
 } // namespace
 
-raw_ostream &operator<<(raw_ostream &OS, const DiagBase &D) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const DiagBase &D) {
   OS << "[";
   if (!D.InsideMainFile)
     OS << D.File << ":";
@@ -198,7 +197,7 @@ raw_ostream &operator<<(raw_ostream &OS,
   return OS << D.Message;
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const Fix &F) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Fix &F) {
   OS << F.Message << " {";
   const char *Sep = "";
   for (const auto &Edit : F.Edits) {
@@ -208,7 +207,7 @@ raw_ostream &operator<<(raw_ostream &OS,
   return OS << "}";
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const Diag &D) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diag &D) {
   OS << static_cast<const DiagBase &>(D);
   if (!D.Notes.empty()) {
     OS << ", notes: {";
@@ -240,9 +239,9 @@ CodeAction toCodeAction(const Fix &F, co
   return Action;
 }
 
-void toLSPDiags(const Diag &D, const URIForFile &File,
-                const ClangdDiagnosticOptions &Opts,
-                function_ref<void(clangd::Diagnostic, ArrayRef<Fix>)> OutFn) {
+void toLSPDiags(
+    const Diag &D, const URIForFile &File, const ClangdDiagnosticOptions &Opts,
+    llvm::function_ref<void(clangd::Diagnostic, llvm::ArrayRef<Fix>)> OutFn) {
   auto FillBasicFields = [](const DiagBase &D) -> clangd::Diagnostic {
     clangd::Diagnostic Res;
     Res.range = D.Range;
@@ -269,7 +268,7 @@ void toLSPDiags(const Diag &D, const URI
       continue;
     clangd::Diagnostic Res = FillBasicFields(Note);
     Res.message = noteMessage(D, Note);
-    OutFn(std::move(Res), ArrayRef<Fix>());
+    OutFn(std::move(Res), llvm::ArrayRef<Fix>());
   }
 }
 
@@ -315,7 +314,7 @@ void StoreDiags::HandleDiagnostic(Diagno
 
   auto FillDiagBase = [&](DiagBase &D) {
     D.Range = diagnosticRange(Info, *LangOpts);
-    SmallString<64> Message;
+    llvm::SmallString<64> Message;
     Info.FormatDiagnostic(Message);
     D.Message = Message.str();
     D.InsideMainFile = InsideMainFile;
@@ -333,7 +332,7 @@ void StoreDiags::HandleDiagnostic(Diagno
     if (!InsideMainFile)
       return false;
 
-    SmallVector<TextEdit, 1> Edits;
+    llvm::SmallVector<TextEdit, 1> Edits;
     for (auto &FixIt : Info.getFixItHints()) {
       if (!isInsideMainFile(FixIt.RemoveRange.getBegin(),
                             Info.getSourceManager()))
@@ -341,16 +340,16 @@ void StoreDiags::HandleDiagnostic(Diagno
       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())

Modified: clang-tools-extra/trunk/clangd/DraftStore.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/DraftStore.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/DraftStore.cpp (original)
+++ clang-tools-extra/trunk/clangd/DraftStore.cpp Mon Jan  7 07:45:19 2019
@@ -11,11 +11,10 @@
 #include "SourceCode.h"
 #include "llvm/Support/Errc.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
-Optional<std::string> DraftStore::getDraft(PathRef File) const {
+llvm::Optional<std::string> DraftStore::getDraft(PathRef File) const {
   std::lock_guard<std::mutex> Lock(Mutex);
 
   auto It = Drafts.find(File);
@@ -35,20 +34,19 @@ std::vector<Path> DraftStore::getActiveF
   return ResultVector;
 }
 
-void DraftStore::addDraft(PathRef File, StringRef Contents) {
+void DraftStore::addDraft(PathRef File, llvm::StringRef Contents) {
   std::lock_guard<std::mutex> Lock(Mutex);
 
   Drafts[File] = Contents;
 }
 
-Expected<std::string>
-DraftStore::updateDraft(PathRef File,
-                        ArrayRef<TextDocumentContentChangeEvent> Changes) {
+llvm::Expected<std::string> DraftStore::updateDraft(
+    PathRef File, llvm::ArrayRef<TextDocumentContentChangeEvent> Changes) {
   std::lock_guard<std::mutex> Lock(Mutex);
 
   auto EntryIt = Drafts.find(File);
   if (EntryIt == Drafts.end()) {
-    return make_error<StringError>(
+    return llvm::make_error<llvm::StringError>(
         "Trying to do incremental update on non-added document: " + File,
         llvm::errc::invalid_argument);
   }
@@ -62,19 +60,21 @@ DraftStore::updateDraft(PathRef File,
     }
 
     const Position &Start = Change.range->start;
-    Expected<size_t> StartIndex = positionToOffset(Contents, Start, false);
+    llvm::Expected<size_t> StartIndex =
+        positionToOffset(Contents, Start, false);
     if (!StartIndex)
       return StartIndex.takeError();
 
     const Position &End = Change.range->end;
-    Expected<size_t> EndIndex = positionToOffset(Contents, End, false);
+    llvm::Expected<size_t> EndIndex = positionToOffset(Contents, End, false);
     if (!EndIndex)
       return EndIndex.takeError();
 
     if (*EndIndex < *StartIndex)
-      return make_error<StringError>(
-          formatv("Range's end position ({0}) is before start position ({1})",
-                  End, Start),
+      return llvm::make_error<llvm::StringError>(
+          llvm::formatv(
+              "Range's end position ({0}) is before start position ({1})", End,
+              Start),
           llvm::errc::invalid_argument);
 
     // Since the range length between two LSP positions is dependent on the
@@ -88,10 +88,10 @@ DraftStore::updateDraft(PathRef File,
         lspLength(Contents.substr(*StartIndex, *EndIndex - *StartIndex));
 
     if (Change.rangeLength && ComputedRangeLength != *Change.rangeLength)
-      return make_error<StringError>(
-          formatv("Change's rangeLength ({0}) doesn't match the "
-                  "computed range length ({1}).",
-                  *Change.rangeLength, *EndIndex - *StartIndex),
+      return llvm::make_error<llvm::StringError>(
+          llvm::formatv("Change's rangeLength ({0}) doesn't match the "
+                        "computed range length ({1}).",
+                        *Change.rangeLength, *EndIndex - *StartIndex),
           llvm::errc::invalid_argument);
 
     std::string NewContents;

Modified: clang-tools-extra/trunk/clangd/ExpectedTypes.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ExpectedTypes.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/ExpectedTypes.cpp (original)
+++ clang-tools-extra/trunk/clangd/ExpectedTypes.cpp Mon Jan  7 07:45:19 2019
@@ -5,8 +5,6 @@
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/STLExtras.h"
 
-using namespace llvm;
-
 namespace clang {
 namespace clangd {
 namespace {
@@ -33,7 +31,8 @@ static const Type *toEquivClass(ASTConte
   return T.getTypePtr();
 }
 
-static Optional<QualType> typeOfCompletion(const CodeCompletionResult &R) {
+static llvm::Optional<QualType>
+typeOfCompletion(const CodeCompletionResult &R) {
   auto *VD = dyn_cast_or_null<ValueDecl>(R.Declaration);
   if (!VD)
     return None; // We handle only variables and functions below.
@@ -49,13 +48,13 @@ static Optional<QualType> typeOfCompleti
 }
 } // namespace
 
-Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
+llvm::Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
   if (T.isNull())
     return None;
   const Type *C = toEquivClass(Ctx, T);
   if (!C)
     return None;
-  SmallString<128> Encoded;
+  llvm::SmallString<128> Encoded;
   if (index::generateUSRForType(QualType(C, 0), Ctx, Encoded))
     return None;
   return OpaqueType(Encoded.str());
@@ -63,11 +62,12 @@ Optional<OpaqueType> OpaqueType::encode(
 
 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);

Modified: clang-tools-extra/trunk/clangd/FS.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FS.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/FS.cpp (original)
+++ clang-tools-extra/trunk/clangd/FS.cpp Mon Jan  7 07:45:19 2019
@@ -12,17 +12,17 @@
 #include "llvm/ADT/None.h"
 #include "llvm/Support/Path.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
-PreambleFileStatusCache::PreambleFileStatusCache(StringRef MainFilePath)
+PreambleFileStatusCache::PreambleFileStatusCache(llvm::StringRef MainFilePath)
     : MainFilePath(MainFilePath) {
-  assert(sys::path::is_absolute(MainFilePath));
+  assert(llvm::sys::path::is_absolute(MainFilePath));
 }
 
-void PreambleFileStatusCache::update(const vfs::FileSystem &FS, vfs::Status S) {
-  SmallString<32> PathStore(S.getName());
+void PreambleFileStatusCache::update(const llvm::vfs::FileSystem &FS,
+                                     llvm::vfs::Status S) {
+  llvm::SmallString<32> PathStore(S.getName());
   if (FS.makeAbsolute(PathStore))
     return;
   // Do not cache status for the main file.
@@ -32,25 +32,27 @@ void PreambleFileStatusCache::update(con
   StatCache.insert({PathStore, std::move(S)});
 }
 
-Optional<vfs::Status> PreambleFileStatusCache::lookup(StringRef File) const {
+llvm::Optional<llvm::vfs::Status>
+PreambleFileStatusCache::lookup(llvm::StringRef File) const {
   auto I = StatCache.find(File);
   if (I != StatCache.end())
     return I->getValue();
   return None;
 }
 
-IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getProducingFS(
-    IntrusiveRefCntPtr<vfs::FileSystem> FS) {
+llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
+PreambleFileStatusCache::getProducingFS(
+    llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) {
   // This invalidates old status in cache if files are re-`open()`ed or
   // re-`stat()`ed in case file status has changed during preamble build.
-  class CollectFS : public vfs::ProxyFileSystem {
+  class CollectFS : public llvm::vfs::ProxyFileSystem {
   public:
-    CollectFS(IntrusiveRefCntPtr<vfs::FileSystem> FS,
+    CollectFS(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
               PreambleFileStatusCache &StatCache)
         : ProxyFileSystem(std::move(FS)), StatCache(StatCache) {}
 
-    ErrorOr<std::unique_ptr<vfs::File>>
-    openFileForRead(const Twine &Path) override {
+    llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
+    openFileForRead(const llvm::Twine &Path) override {
       auto File = getUnderlyingFS().openFileForRead(Path);
       if (!File || !*File)
         return File;
@@ -64,7 +66,7 @@ IntrusiveRefCntPtr<vfs::FileSystem> Prea
       return File;
     }
 
-    ErrorOr<vfs::Status> status(const Twine &Path) override {
+    llvm::ErrorOr<llvm::vfs::Status> status(const llvm::Twine &Path) override {
       auto S = getUnderlyingFS().status(Path);
       if (S)
         StatCache.update(getUnderlyingFS(), *S);
@@ -74,18 +76,20 @@ IntrusiveRefCntPtr<vfs::FileSystem> Prea
   private:
     PreambleFileStatusCache &StatCache;
   };
-  return IntrusiveRefCntPtr<CollectFS>(new CollectFS(std::move(FS), *this));
+  return llvm::IntrusiveRefCntPtr<CollectFS>(
+      new CollectFS(std::move(FS), *this));
 }
 
-IntrusiveRefCntPtr<vfs::FileSystem> PreambleFileStatusCache::getConsumingFS(
-    IntrusiveRefCntPtr<vfs::FileSystem> FS) const {
-  class CacheVFS : public vfs::ProxyFileSystem {
+llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
+PreambleFileStatusCache::getConsumingFS(
+    llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) const {
+  class CacheVFS : public llvm::vfs::ProxyFileSystem {
   public:
-    CacheVFS(IntrusiveRefCntPtr<vfs::FileSystem> FS,
+    CacheVFS(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
              const PreambleFileStatusCache &StatCache)
         : ProxyFileSystem(std::move(FS)), StatCache(StatCache) {}
 
-    ErrorOr<vfs::Status> status(const Twine &Path) override {
+    llvm::ErrorOr<llvm::vfs::Status> status(const llvm::Twine &Path) override {
       if (auto S = StatCache.lookup(Path.str()))
         return *S;
       return getUnderlyingFS().status(Path);
@@ -94,7 +98,7 @@ IntrusiveRefCntPtr<vfs::FileSystem> Prea
   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

Modified: clang-tools-extra/trunk/clangd/FSProvider.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FSProvider.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/FSProvider.cpp (original)
+++ clang-tools-extra/trunk/clangd/FSProvider.cpp Mon Jan  7 07:45:19 2019
@@ -15,8 +15,6 @@
 #include "llvm/Support/VirtualFileSystem.h"
 #include <memory>
 
-using namespace llvm;
-
 namespace clang {
 namespace clangd {
 
@@ -28,9 +26,9 @@ public:
   explicit VolatileFileSystem(llvm::IntrusiveRefCntPtr<FileSystem> FS)
       : ProxyFileSystem(std::move(FS)) {}
 
-  llvm::ErrorOr<std::unique_ptr<vfs::File>>
-  openFileForRead(const Twine &InPath) override {
-    SmallString<128> Path;
+  llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
+  openFileForRead(const llvm::Twine &InPath) override {
+    llvm::SmallString<128> Path;
     InPath.toVector(Path);
 
     auto File = getUnderlyingFS().openFileForRead(Path);
@@ -38,28 +36,30 @@ public:
       return File;
     // Try to guess preamble files, they can be memory-mapped even on Windows as
     // clangd has exclusive access to those.
-    StringRef FileName = llvm::sys::path::filename(Path);
+    llvm::StringRef FileName = llvm::sys::path::filename(Path);
     if (FileName.startswith("preamble-") && FileName.endswith(".pch"))
       return File;
     return std::unique_ptr<VolatileFile>(new VolatileFile(std::move(*File)));
   }
 
 private:
-  class VolatileFile : public vfs::File {
+  class VolatileFile : public llvm::vfs::File {
   public:
-    VolatileFile(std::unique_ptr<vfs::File> Wrapped)
+    VolatileFile(std::unique_ptr<llvm::vfs::File> Wrapped)
         : Wrapped(std::move(Wrapped)) {
       assert(this->Wrapped);
     }
 
     virtual llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
-    getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
-              bool /*IsVolatile*/) override {
+    getBuffer(const llvm::Twine &Name, int64_t FileSize,
+              bool RequiresNullTerminator, bool /*IsVolatile*/) override {
       return Wrapped->getBuffer(Name, FileSize, RequiresNullTerminator,
                                 /*IsVolatile=*/true);
     }
 
-    llvm::ErrorOr<vfs::Status> status() override { return Wrapped->status(); }
+    llvm::ErrorOr<llvm::vfs::Status> status() override {
+      return Wrapped->status();
+    }
     llvm::ErrorOr<std::string> getName() override { return Wrapped->getName(); }
     std::error_code close() override { return Wrapped->close(); }
 
@@ -77,7 +77,7 @@ clang::clangd::RealFileSystemProvider::g
 #ifdef _WIN32
   return new VolatileFileSystem(vfs::getRealFileSystem());
 #else
-  return vfs::getRealFileSystem();
+  return llvm::vfs::getRealFileSystem();
 #endif
 }
 } // namespace clangd

Modified: clang-tools-extra/trunk/clangd/FileDistance.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FileDistance.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/FileDistance.cpp (original)
+++ clang-tools-extra/trunk/clangd/FileDistance.cpp Mon Jan  7 07:45:19 2019
@@ -36,7 +36,6 @@
 #include "llvm/ADT/STLExtras.h"
 #include <queue>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -45,21 +44,23 @@ namespace clangd {
 //   C:\foo\bar --> /c:/foo/bar
 //   /foo/      --> /foo
 //   a/b/c      --> /a/b/c
-static SmallString<128> canonicalize(StringRef Path) {
-  SmallString<128> Result = Path.rtrim('/');
-  native(Result, sys::path::Style::posix);
+static llvm::SmallString<128> canonicalize(llvm::StringRef Path) {
+  llvm::SmallString<128> Result = Path.rtrim('/');
+  native(Result, llvm::sys::path::Style::posix);
   if (Result.empty() || Result.front() != '/')
     Result.insert(Result.begin(), '/');
   return Result;
 }
 
 constexpr const unsigned FileDistance::Unreachable;
-const hash_code FileDistance::RootHash = hash_value(StringRef("/"));
+const llvm::hash_code FileDistance::RootHash =
+    llvm::hash_value(llvm::StringRef("/"));
 
-FileDistance::FileDistance(StringMap<SourceParams> Sources,
+FileDistance::FileDistance(llvm::StringMap<SourceParams> Sources,
                            const FileDistanceOptions &Opts)
     : Opts(Opts) {
-  DenseMap<hash_code, SmallVector<hash_code, 4>> DownEdges;
+  llvm::DenseMap<llvm::hash_code, llvm::SmallVector<llvm::hash_code, 4>>
+      DownEdges;
   // Compute the best distance following only up edges.
   // Keep track of down edges, in case we can use them to improve on this.
   for (const auto &S : Sources) {
@@ -67,13 +68,13 @@ FileDistance::FileDistance(StringMap<Sou
     dlog("Source {0} = {1}, MaxUp = {2}", Canonical, S.second.Cost,
          S.second.MaxUpTraversals);
     // Walk up to ancestors of this source, assigning cost.
-    StringRef Rest = Canonical;
-    hash_code Hash = hash_value(Rest);
+    llvm::StringRef Rest = Canonical;
+    llvm::hash_code Hash = llvm::hash_value(Rest);
     for (unsigned I = 0; !Rest.empty(); ++I) {
-      Rest = parent_path(Rest, sys::path::Style::posix);
-      auto NextHash = hash_value(Rest);
+      Rest = parent_path(Rest, llvm::sys::path::Style::posix);
+      auto NextHash = llvm::hash_value(Rest);
       auto &Down = DownEdges[NextHash];
-      if (!is_contained(Down, Hash))
+      if (!llvm::is_contained(Down, Hash))
         Down.push_back(Hash);
       // We can't just break after MaxUpTraversals, must still set DownEdges.
       if (I > S.getValue().MaxUpTraversals) {
@@ -96,8 +97,8 @@ FileDistance::FileDistance(StringMap<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(StringRef(""))))
+  std::queue<llvm::hash_code> Next;
+  for (auto Child : DownEdges.lookup(llvm::hash_value(llvm::StringRef(""))))
     Next.push(Child);
   while (!Next.empty()) {
     auto Parent = Next.front();
@@ -115,14 +116,14 @@ FileDistance::FileDistance(StringMap<Sou
   }
 }
 
-unsigned FileDistance::distance(StringRef Path) {
+unsigned FileDistance::distance(llvm::StringRef Path) {
   auto Canonical = canonicalize(Path);
   unsigned Cost = Unreachable;
-  SmallVector<hash_code, 16> Ancestors;
+  llvm::SmallVector<llvm::hash_code, 16> Ancestors;
   // Walk up ancestors until we find a path we know the distance for.
-  for (StringRef Rest = Canonical; !Rest.empty();
-       Rest = parent_path(Rest, sys::path::Style::posix)) {
-    auto Hash = hash_value(Rest);
+  for (llvm::StringRef Rest = Canonical; !Rest.empty();
+       Rest = parent_path(Rest, llvm::sys::path::Style::posix)) {
+    auto Hash = llvm::hash_value(Rest);
     if (Hash == RootHash && !Ancestors.empty() &&
         !Opts.AllowDownTraversalFromRoot) {
       Cost = Unreachable;
@@ -137,7 +138,7 @@ unsigned FileDistance::distance(StringRe
   }
   // Now we know the costs for (known node, queried node].
   // Fill these in, walking down the directory tree.
-  for (hash_code Hash : reverse(Ancestors)) {
+  for (llvm::hash_code Hash : llvm::reverse(Ancestors)) {
     if (Cost != Unreachable)
       Cost += Opts.DownCost;
     Cache.try_emplace(Hash, Cost);
@@ -146,8 +147,8 @@ unsigned FileDistance::distance(StringRe
   return Cost;
 }
 
-unsigned URIDistance::distance(StringRef URI) {
-  auto R = Cache.try_emplace(hash_value(URI), FileDistance::Unreachable);
+unsigned URIDistance::distance(llvm::StringRef URI) {
+  auto R = Cache.try_emplace(llvm::hash_value(URI), FileDistance::Unreachable);
   if (!R.second)
     return R.first->getSecond();
   if (auto U = clangd::URI::parse(URI)) {
@@ -159,15 +160,15 @@ unsigned URIDistance::distance(StringRef
   return R.first->second;
 }
 
-FileDistance &URIDistance::forScheme(StringRef Scheme) {
+FileDistance &URIDistance::forScheme(llvm::StringRef Scheme) {
   auto &Delegate = ByScheme[Scheme];
   if (!Delegate) {
-    StringMap<SourceParams> SchemeSources;
+    llvm::StringMap<SourceParams> SchemeSources;
     for (const auto &Source : Sources) {
       if (auto U = clangd::URI::create(Source.getKey(), Scheme))
         SchemeSources.try_emplace(U->body(), Source.getValue());
       else
-        consumeError(U.takeError());
+        llvm::consumeError(U.takeError());
     }
     dlog("FileDistance for scheme {0}: {1}/{2} sources", Scheme,
          SchemeSources.size(), Sources.size());
@@ -176,21 +177,23 @@ FileDistance &URIDistance::forScheme(Str
   return *Delegate;
 }
 
-static std::pair<std::string, int> scopeToPath(StringRef Scope) {
-  SmallVector<StringRef, 4> Split;
+static std::pair<std::string, int> scopeToPath(llvm::StringRef Scope) {
+  llvm::SmallVector<llvm::StringRef, 4> Split;
   Scope.split(Split, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
-  return {"/" + join(Split, "/"), Split.size()};
+  return {"/" + llvm::join(Split, "/"), Split.size()};
 }
 
-static FileDistance createScopeFileDistance(ArrayRef<std::string> QueryScopes) {
+static FileDistance
+createScopeFileDistance(llvm::ArrayRef<std::string> QueryScopes) {
   FileDistanceOptions Opts;
   Opts.UpCost = 2;
   Opts.DownCost = 4;
   Opts.AllowDownTraversalFromRoot = false;
 
-  StringMap<SourceParams> Sources;
-  StringRef Preferred = QueryScopes.empty() ? "" : QueryScopes.front().c_str();
-  for (StringRef S : QueryScopes) {
+  llvm::StringMap<SourceParams> Sources;
+  llvm::StringRef Preferred =
+      QueryScopes.empty() ? "" : QueryScopes.front().c_str();
+  for (llvm::StringRef S : QueryScopes) {
     SourceParams Param;
     // Penalize the global scope even it's preferred, as all projects can define
     // symbols in it, and there is pattern where using-namespace is used in
@@ -209,10 +212,10 @@ static FileDistance createScopeFileDista
   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);
 }
 

Modified: clang-tools-extra/trunk/clangd/FindSymbols.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FindSymbols.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/FindSymbols.cpp (original)
+++ clang-tools-extra/trunk/clangd/FindSymbols.cpp Mon Jan  7 07:45:19 2019
@@ -25,7 +25,6 @@
 
 #define DEBUG_TYPE "FindSymbols"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -100,9 +99,9 @@ struct ScoredSymbolGreater {
 
 } // namespace
 
-Expected<std::vector<SymbolInformation>>
-getWorkspaceSymbols(StringRef Query, int Limit, const SymbolIndex *const Index,
-                    StringRef HintPath) {
+llvm::Expected<std::vector<SymbolInformation>>
+getWorkspaceSymbols(llvm::StringRef Query, int Limit,
+                    const SymbolIndex *const Index, llvm::StringRef HintPath) {
   std::vector<SymbolInformation> Result;
   if (Query.empty() || !Index)
     return Result;
@@ -153,7 +152,7 @@ getWorkspaceSymbols(StringRef Query, int
     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};
 

Modified: clang-tools-extra/trunk/clangd/FuzzyMatch.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FuzzyMatch.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/FuzzyMatch.cpp (original)
+++ clang-tools-extra/trunk/clangd/FuzzyMatch.cpp Mon Jan  7 07:45:19 2019
@@ -60,7 +60,6 @@
 #include "llvm/ADT/Optional.h"
 #include "llvm/Support/Format.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -75,7 +74,7 @@ static constexpr int AwfulScore = -(1 <<
 static bool isAwful(int S) { return S < AwfulScore / 2; }
 static constexpr int PerfectBonus = 3; // Perfect per-pattern-char score.
 
-FuzzyMatcher::FuzzyMatcher(StringRef Pattern)
+FuzzyMatcher::FuzzyMatcher(llvm::StringRef Pattern)
     : PatN(std::min<int>(MaxPat, Pattern.size())),
       ScoreScale(PatN ? float{1} / (PerfectBonus * PatN) : 0), WordN(0) {
   std::copy(Pattern.begin(), Pattern.begin() + PatN, Pat);
@@ -87,20 +86,20 @@ FuzzyMatcher::FuzzyMatcher(StringRef Pat
     for (int W = 0; W < P; ++W)
       for (Action A : {Miss, Match})
         Scores[P][W][A] = {AwfulScore, Miss};
-  PatTypeSet =
-      calculateRoles(StringRef(Pat, PatN), makeMutableArrayRef(PatRole, PatN));
+  PatTypeSet = calculateRoles(llvm::StringRef(Pat, PatN),
+                              llvm::makeMutableArrayRef(PatRole, PatN));
 }
 
-Optional<float> FuzzyMatcher::match(StringRef Word) {
+llvm::Optional<float> FuzzyMatcher::match(llvm::StringRef Word) {
   if (!(WordContainsPattern = init(Word)))
-    return None;
+    return llvm::None;
   if (!PatN)
     return 1;
   buildGraph();
   auto Best = std::max(Scores[PatN][WordN][Miss].Score,
                        Scores[PatN][WordN][Match].Score);
   if (isAwful(Best))
-    return None;
+    return llvm::None;
   float Score =
       ScoreScale * std::min(PerfectBonus * PatN, std::max<int>(0, Best));
   // If the pattern is as long as the word, we have an exact string match,
@@ -153,7 +152,8 @@ constexpr static uint8_t CharRoles[] = {
 template <typename T> static T packedLookup(const uint8_t *Data, int I) {
   return static_cast<T>((Data[I >> 2] >> ((I & 3) * 2)) & 3);
 }
-CharTypeSet calculateRoles(StringRef Text, MutableArrayRef<CharRole> Roles) {
+CharTypeSet calculateRoles(llvm::StringRef Text,
+                           llvm::MutableArrayRef<CharRole> Roles) {
   assert(Text.size() == Roles.size());
   if (Text.size() == 0)
     return 0;
@@ -179,7 +179,7 @@ CharTypeSet calculateRoles(StringRef Tex
 
 // Sets up the data structures matching Word.
 // Returns false if we can cheaply determine that no match is possible.
-bool FuzzyMatcher::init(StringRef NewWord) {
+bool FuzzyMatcher::init(llvm::StringRef NewWord) {
   WordN = std::min<int>(MaxWord, NewWord.size());
   if (PatN > WordN)
     return false;
@@ -200,8 +200,8 @@ bool FuzzyMatcher::init(StringRef NewWor
   // FIXME: some words are hard to tokenize algorithmically.
   // e.g. vsprintf is V S Print F, and should match [pri] but not [int].
   // We could add a tokenization dictionary for common stdlib names.
-  WordTypeSet = calculateRoles(StringRef(Word, WordN),
-                               makeMutableArrayRef(WordRole, WordN));
+  WordTypeSet = calculateRoles(llvm::StringRef(Word, WordN),
+                               llvm::makeMutableArrayRef(WordRole, WordN));
   return true;
 }
 
@@ -299,13 +299,13 @@ int FuzzyMatcher::matchBonus(int P, int
   return S;
 }
 
-SmallString<256> FuzzyMatcher::dumpLast(raw_ostream &OS) const {
-  SmallString<256> Result;
-  OS << "=== Match \"" << StringRef(Word, WordN) << "\" against ["
-     << StringRef(Pat, PatN) << "] ===\n";
+llvm::SmallString<256> FuzzyMatcher::dumpLast(llvm::raw_ostream &OS) const {
+  llvm::SmallString<256> Result;
+  OS << "=== Match \"" << llvm::StringRef(Word, WordN) << "\" against ["
+     << llvm::StringRef(Pat, PatN) << "] ===\n";
   if (PatN == 0) {
     OS << "Pattern is empty: perfect match.\n";
-    return Result = StringRef(Word, WordN);
+    return Result = llvm::StringRef(Word, WordN);
   }
   if (WordN == 0) {
     OS << "Word is empty: no match.\n";
@@ -349,28 +349,28 @@ SmallString<256> FuzzyMatcher::dumpLast(
   if (A[WordN - 1] == Match)
     Result.push_back(']');
 
-  for (char C : StringRef(Word, WordN))
+  for (char C : llvm::StringRef(Word, WordN))
     OS << " " << C << " ";
   OS << "\n";
   for (int I = 0, J = 0; I < WordN; I++)
     OS << " " << (A[I] == Match ? Pat[J++] : ' ') << " ";
   OS << "\n";
   for (int I = 0; I < WordN; I++)
-    OS << format("%2d ", S[I]);
+    OS << llvm::format("%2d ", S[I]);
   OS << "\n";
 
   OS << "\nSegmentation:";
-  OS << "\n'" << StringRef(Word, WordN) << "'\n ";
+  OS << "\n'" << llvm::StringRef(Word, WordN) << "'\n ";
   for (int I = 0; I < WordN; ++I)
     OS << "?-+ "[static_cast<int>(WordRole[I])];
-  OS << "\n[" << StringRef(Pat, PatN) << "]\n ";
+  OS << "\n[" << llvm::StringRef(Pat, PatN) << "]\n ";
   for (int I = 0; I < PatN; ++I)
     OS << "?-+ "[static_cast<int>(PatRole[I])];
   OS << "\n";
 
   OS << "\nScoring table (last-Miss, last-Match):\n";
   OS << " |    ";
-  for (char C : StringRef(Word, WordN))
+  for (char C : llvm::StringRef(Word, WordN))
     OS << "  " << C << " ";
   OS << "\n";
   OS << "-+----" << std::string(WordN * 4, '-') << "\n";
@@ -379,8 +379,8 @@ SmallString<256> FuzzyMatcher::dumpLast(
       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 << "    ";
       }

Modified: clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp (original)
+++ clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp Mon Jan  7 07:45:19 2019
@@ -13,7 +13,6 @@
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -32,22 +31,24 @@ GlobalCompilationDatabase::getFallbackCo
   std::vector<std::string> Argv = {getFallbackClangPath()};
   // Clang treats .h files as C by default, resulting in unhelpful diagnostics.
   // Parsing as Objective C++ is friendly to more cases.
-  if (sys::path::extension(File) == ".h")
+  if (llvm::sys::path::extension(File) == ".h")
     Argv.push_back("-xobjective-c++-header");
   Argv.push_back(File);
-  return tooling::CompileCommand(sys::path::parent_path(File),
-                                 sys::path::filename(File), std::move(Argv),
+  return tooling::CompileCommand(llvm::sys::path::parent_path(File),
+                                 llvm::sys::path::filename(File),
+                                 std::move(Argv),
                                  /*Output=*/"");
 }
 
 DirectoryBasedGlobalCompilationDatabase::
-    DirectoryBasedGlobalCompilationDatabase(Optional<Path> CompileCommandsDir)
+    DirectoryBasedGlobalCompilationDatabase(
+        llvm::Optional<Path> CompileCommandsDir)
     : CompileCommandsDir(std::move(CompileCommandsDir)) {}
 
 DirectoryBasedGlobalCompilationDatabase::
     ~DirectoryBasedGlobalCompilationDatabase() = default;
 
-Optional<tooling::CompileCommand>
+llvm::Optional<tooling::CompileCommand>
 DirectoryBasedGlobalCompilationDatabase::getCompileCommand(
     PathRef File, ProjectInfo *Project) const {
   if (auto CDB = getCDBForFile(File, Project)) {
@@ -77,7 +78,7 @@ DirectoryBasedGlobalCompilationDatabase:
 tooling::CompilationDatabase *
 DirectoryBasedGlobalCompilationDatabase::getCDBForFile(
     PathRef File, ProjectInfo *Project) const {
-  namespace path = sys::path;
+  namespace path = llvm::sys::path;
   assert((path::is_absolute(File, path::Style::posix) ||
           path::is_absolute(File, path::Style::windows)) &&
          "path must be absolute");
@@ -113,7 +114,7 @@ OverlayCDB::OverlayCDB(const GlobalCompi
     });
 }
 
-Optional<tooling::CompileCommand>
+llvm::Optional<tooling::CompileCommand>
 OverlayCDB::getCompileCommand(PathRef File, ProjectInfo *Project) const {
   {
     std::lock_guard<std::mutex> Lock(Mutex);

Modified: clang-tools-extra/trunk/clangd/Headers.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Headers.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Headers.cpp (original)
+++ clang-tools-extra/trunk/clangd/Headers.cpp Mon Jan  7 07:45:19 2019
@@ -17,7 +17,6 @@
 #include "clang/Lex/HeaderSearch.h"
 #include "llvm/Support/Path.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -30,9 +29,10 @@ public:
   // Record existing #includes - both written and resolved paths. Only #includes
   // in the main file are collected.
   void InclusionDirective(SourceLocation HashLoc, const Token & /*IncludeTok*/,
-                          StringRef FileName, bool IsAngled,
+                          llvm::StringRef FileName, bool IsAngled,
                           CharSourceRange FilenameRange, const FileEntry *File,
-                          StringRef /*SearchPath*/, StringRef /*RelativePath*/,
+                          llvm::StringRef /*SearchPath*/,
+                          llvm::StringRef /*RelativePath*/,
                           const Module * /*Imported*/,
                           SrcMgr::CharacteristicKind FileKind) override {
     if (SM.isWrittenInMainFile(HashLoc)) {
@@ -65,13 +65,13 @@ private:
 
 } // namespace
 
-bool isLiteralInclude(StringRef Include) {
+bool isLiteralInclude(llvm::StringRef Include) {
   return Include.startswith("<") || Include.startswith("\"");
 }
 
 bool HeaderFile::valid() const {
   return (Verbatim && isLiteralInclude(File)) ||
-         (!Verbatim && sys::path::is_absolute(File));
+         (!Verbatim && llvm::sys::path::is_absolute(File));
 }
 
 std::unique_ptr<PPCallbacks>
@@ -80,9 +80,9 @@ collectIncludeStructureCallback(const So
   return llvm::make_unique<RecordHeaders>(SM, Out);
 }
 
-void IncludeStructure::recordInclude(StringRef IncludingName,
-                                     StringRef IncludedName,
-                                     StringRef IncludedRealName) {
+void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
+                                     llvm::StringRef IncludedName,
+                                     llvm::StringRef IncludedRealName) {
   auto Child = fileIndex(IncludedName);
   if (!IncludedRealName.empty() && RealPathNames[Child].empty())
     RealPathNames[Child] = IncludedRealName;
@@ -90,19 +90,20 @@ void IncludeStructure::recordInclude(Str
   IncludeChildren[Parent].push_back(Child);
 }
 
-unsigned IncludeStructure::fileIndex(StringRef Name) {
+unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
   auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
   if (R.second)
     RealPathNames.emplace_back();
   return R.first->getValue();
 }
 
-StringMap<unsigned> IncludeStructure::includeDepth(StringRef Root) const {
+llvm::StringMap<unsigned>
+IncludeStructure::includeDepth(llvm::StringRef Root) const {
   // Include depth 0 is the main file only.
-  StringMap<unsigned> Result;
+  llvm::StringMap<unsigned> Result;
   Result[Root] = 0;
   std::vector<unsigned> CurrentLevel;
-  DenseSet<unsigned> Seen;
+  llvm::DenseSet<unsigned> Seen;
   auto It = NameToIndex.find(Root);
   if (It != NameToIndex.end()) {
     CurrentLevel.push_back(It->second);
@@ -142,7 +143,7 @@ bool IncludeInserter::shouldInsertInclud
   assert(DeclaringHeader.valid() && InsertedHeader.valid());
   if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
     return false;
-  auto Included = [&](StringRef Header) {
+  auto Included = [&](llvm::StringRef Header) {
     return IncludedHeaders.find(Header) != IncludedHeaders.end();
   };
   return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
@@ -164,8 +165,9 @@ IncludeInserter::calculateIncludePath(co
   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);

Modified: clang-tools-extra/trunk/clangd/JSONTransport.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/JSONTransport.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/JSONTransport.cpp (original)
+++ clang-tools-extra/trunk/clangd/JSONTransport.cpp Mon Jan  7 07:45:19 2019
@@ -11,66 +11,68 @@
 #include "Transport.h"
 #include "llvm/Support/Errno.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
 
-json::Object encodeError(Error E) {
+llvm::json::Object encodeError(llvm::Error E) {
   std::string Message;
   ErrorCode Code = ErrorCode::UnknownErrorCode;
-  if (Error Unhandled =
-          handleErrors(std::move(E), [&](const LSPError &L) -> Error {
+  if (llvm::Error Unhandled = llvm::handleErrors(
+          std::move(E), [&](const LSPError &L) -> llvm::Error {
             Message = L.Message;
             Code = L.Code;
-            return Error::success();
+            return llvm::Error::success();
           }))
-    Message = toString(std::move(Unhandled));
+    Message = llvm::toString(std::move(Unhandled));
 
-  return json::Object{
+  return llvm::json::Object{
       {"message", std::move(Message)},
       {"code", int64_t(Code)},
   };
 }
 
-Error decodeError(const json::Object &O) {
+llvm::Error decodeError(const llvm::json::Object &O) {
   std::string Msg = O.getString("message").getValueOr("Unspecified error");
   if (auto Code = O.getInteger("code"))
-    return make_error<LSPError>(std::move(Msg), ErrorCode(*Code));
-  return make_error<StringError>(std::move(Msg), inconvertibleErrorCode());
+    return llvm::make_error<LSPError>(std::move(Msg), ErrorCode(*Code));
+  return llvm::make_error<llvm::StringError>(std::move(Msg),
+                                             llvm::inconvertibleErrorCode());
 }
 
 class JSONTransport : public Transport {
 public:
-  JSONTransport(std::FILE *In, raw_ostream &Out, raw_ostream *InMirror,
-                bool Pretty, JSONStreamStyle Style)
-      : In(In), Out(Out), InMirror(InMirror ? *InMirror : nulls()),
+  JSONTransport(std::FILE *In, llvm::raw_ostream &Out,
+                llvm::raw_ostream *InMirror, bool Pretty, JSONStreamStyle Style)
+      : In(In), Out(Out), InMirror(InMirror ? *InMirror : llvm::nulls()),
         Pretty(Pretty), Style(Style) {}
 
-  void notify(StringRef Method, json::Value Params) override {
-    sendMessage(json::Object{
+  void notify(llvm::StringRef Method, llvm::json::Value Params) override {
+    sendMessage(llvm::json::Object{
         {"jsonrpc", "2.0"},
         {"method", Method},
         {"params", std::move(Params)},
     });
   }
-  void call(StringRef Method, json::Value Params, json::Value ID) override {
-    sendMessage(json::Object{
+  void call(llvm::StringRef Method, llvm::json::Value Params,
+            llvm::json::Value ID) override {
+    sendMessage(llvm::json::Object{
         {"jsonrpc", "2.0"},
         {"id", std::move(ID)},
         {"method", Method},
         {"params", std::move(Params)},
     });
   }
-  void reply(json::Value ID, Expected<json::Value> Result) override {
+  void reply(llvm::json::Value ID,
+             llvm::Expected<llvm::json::Value> Result) override {
     if (Result) {
-      sendMessage(json::Object{
+      sendMessage(llvm::json::Object{
           {"jsonrpc", "2.0"},
           {"id", std::move(ID)},
           {"result", std::move(*Result)},
       });
     } else {
-      sendMessage(json::Object{
+      sendMessage(llvm::json::Object{
           {"jsonrpc", "2.0"},
           {"id", std::move(ID)},
           {"error", encodeError(Result.takeError())},
@@ -78,33 +80,34 @@ public:
     }
   }
 
-  Error loop(MessageHandler &Handler) override {
+  llvm::Error loop(MessageHandler &Handler) override {
     while (!feof(In)) {
       if (ferror(In))
-        return errorCodeToError(std::error_code(errno, std::system_category()));
+        return llvm::errorCodeToError(
+            std::error_code(errno, std::system_category()));
       if (auto JSON = readRawMessage()) {
-        if (auto Doc = json::parse(*JSON)) {
+        if (auto Doc = llvm::json::parse(*JSON)) {
           vlog(Pretty ? "<<< {0:2}\n" : "<<< {0}\n", *Doc);
           if (!handleMessage(std::move(*Doc), Handler))
-            return Error::success(); // we saw the "exit" notification.
+            return llvm::Error::success(); // we saw the "exit" notification.
         } else {
           // Parse error. Log the raw message.
           vlog("<<< {0}\n", *JSON);
-          elog("JSON parse error: {0}", toString(Doc.takeError()));
+          elog("JSON parse error: {0}", llvm::toString(Doc.takeError()));
         }
       }
     }
-    return errorCodeToError(std::make_error_code(std::errc::io_error));
+    return llvm::errorCodeToError(std::make_error_code(std::errc::io_error));
   }
 
 private:
   // Dispatches incoming message to Handler onNotify/onCall/onReply.
-  bool handleMessage(json::Value Message, MessageHandler &Handler);
+  bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
   // Writes outgoing message to Out stream.
-  void sendMessage(json::Value Message) {
+  void sendMessage(llvm::json::Value Message) {
     std::string S;
-    raw_string_ostream OS(S);
-    OS << formatv(Pretty ? "{0:2}" : "{0}", Message);
+    llvm::raw_string_ostream OS(S);
+    OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
     OS.flush();
     Out << "Content-Length: " << S.size() << "\r\n\r\n" << S;
     Out.flush();
@@ -112,30 +115,31 @@ private:
   }
 
   // Read raw string messages from input stream.
-  Optional<std::string> readRawMessage() {
+  llvm::Optional<std::string> readRawMessage() {
     return Style == JSONStreamStyle::Delimited ? readDelimitedMessage()
                                                : readStandardMessage();
   }
-  Optional<std::string> readDelimitedMessage();
-  Optional<std::string> readStandardMessage();
+  llvm::Optional<std::string> readDelimitedMessage();
+  llvm::Optional<std::string> readStandardMessage();
 
   std::FILE *In;
-  raw_ostream &Out;
-  raw_ostream &InMirror;
+  llvm::raw_ostream &Out;
+  llvm::raw_ostream &InMirror;
   bool Pretty;
   JSONStreamStyle Style;
 };
 
-bool JSONTransport::handleMessage(json::Value Message,
+bool JSONTransport::handleMessage(llvm::json::Value Message,
                                   MessageHandler &Handler) {
   // Message must be an object with "jsonrpc":"2.0".
   auto *Object = Message.getAsObject();
-  if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0")) {
+  if (!Object ||
+      Object->getString("jsonrpc") != llvm::Optional<llvm::StringRef>("2.0")) {
     elog("Not a JSON-RPC 2.0 message: {0:2}", Message);
     return false;
   }
   // ID may be any JSON value. If absent, this is a notification.
-  Optional<json::Value> ID;
+  llvm::Optional<llvm::json::Value> ID;
   if (auto *I = Object->get("id"))
     ID = std::move(*I);
   auto Method = Object->getString("method");
@@ -147,13 +151,13 @@ bool JSONTransport::handleMessage(json::
     if (auto *Err = Object->getObject("error"))
       return Handler.onReply(std::move(*ID), decodeError(*Err));
     // Result should be given, use null if not.
-    json::Value Result = nullptr;
+    llvm::json::Value Result = nullptr;
     if (auto *R = Object->get("result"))
       Result = std::move(*R);
     return Handler.onReply(std::move(*ID), std::move(Result));
   }
   // Params should be given, use null if not.
-  json::Value Params = nullptr;
+  llvm::json::Value Params = nullptr;
   if (auto *P = Object->get("params"))
     Params = std::move(*P);
 
@@ -172,7 +176,7 @@ bool readLine(std::FILE *In, std::string
   for (;;) {
     Out.resize(Size + BufSize);
     // Handle EINTR which is sent when a debugger attaches on some platforms.
-    if (!sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
+    if (!llvm::sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
       return false;
     clearerr(In);
     // If the line contained null bytes, anything after it (including \n) will
@@ -189,17 +193,17 @@ bool readLine(std::FILE *In, std::string
 // Returns None when:
 //  - ferror() or feof() are set.
 //  - Content-Length is missing or empty (protocol error)
-Optional<std::string> JSONTransport::readStandardMessage() {
+llvm::Optional<std::string> JSONTransport::readStandardMessage() {
   // A Language Server Protocol message starts with a set of HTTP headers,
   // delimited  by \r\n, and terminated by an empty line (\r\n).
   unsigned long long ContentLength = 0;
   std::string Line;
   while (true) {
     if (feof(In) || ferror(In) || !readLine(In, Line))
-      return None;
+      return llvm::None;
     InMirror << Line;
 
-    StringRef LineRef(Line);
+    llvm::StringRef LineRef(Line);
 
     // We allow comments in headers. Technically this isn't part
 
@@ -214,7 +218,7 @@ Optional<std::string> JSONTransport::rea
              "The previous value for this message ({0}) was ignored.",
              ContentLength);
       }
-      getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
+      llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
       continue;
     } else if (!LineRef.trim().empty()) {
       // It's another header, ignore it.
@@ -231,24 +235,24 @@ Optional<std::string> JSONTransport::rea
     elog("Refusing to read message with long Content-Length: {0}. "
          "Expect protocol errors",
          ContentLength);
-    return None;
+    return llvm::None;
   }
   if (ContentLength == 0) {
     log("Warning: Missing Content-Length header, or zero-length message.");
-    return None;
+    return llvm::None;
   }
 
   std::string JSON(ContentLength, '\0');
   for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
     // Handle EINTR which is sent when a debugger attaches on some platforms.
-    Read = sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
-                                 ContentLength - Pos, In);
+    Read = llvm::sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
+                                       ContentLength - Pos, In);
     if (Read == 0) {
       elog("Input was aborted. Read only {0} bytes of expected {1}.", Pos,
            ContentLength);
-      return None;
+      return llvm::None;
     }
-    InMirror << StringRef(&JSON[Pos], Read);
+    InMirror << llvm::StringRef(&JSON[Pos], Read);
     clearerr(In); // If we're done, the error was transient. If we're not done,
                   // either it was transient or we'll see it again on retry.
     Pos += Read;
@@ -261,12 +265,12 @@ Optional<std::string> JSONTransport::rea
 // - lines starting with # are ignored.
 // This is a testing path, so favor simplicity over performance here.
 // When returning None, feof() or ferror() will be set.
-Optional<std::string> JSONTransport::readDelimitedMessage() {
+llvm::Optional<std::string> JSONTransport::readDelimitedMessage() {
   std::string JSON;
   std::string Line;
   while (readLine(In, Line)) {
     InMirror << Line;
-    auto LineRef = StringRef(Line).trim();
+    auto LineRef = llvm::StringRef(Line).trim();
     if (LineRef.startswith("#")) // comment
       continue;
 
@@ -279,15 +283,17 @@ Optional<std::string> JSONTransport::rea
 
   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);
 }

Modified: clang-tools-extra/trunk/clangd/Logger.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Logger.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Logger.cpp (original)
+++ clang-tools-extra/trunk/clangd/Logger.cpp Mon Jan  7 07:45:19 2019
@@ -14,7 +14,6 @@
 #include "llvm/Support/raw_ostream.h"
 #include <mutex>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -29,13 +28,14 @@ LoggingSession::LoggingSession(clangd::L
 
 LoggingSession::~LoggingSession() { L = nullptr; }
 
-void detail::log(Logger::Level Level, const formatv_object_base &Message) {
+void detail::log(Logger::Level Level,
+                 const llvm::formatv_object_base &Message) {
   if (L)
     L->log(Level, Message);
   else {
     static std::mutex Mu;
     std::lock_guard<std::mutex> Guard(Mu);
-    errs() << Message << "\n";
+    llvm::errs() << Message << "\n";
   }
 }
 
@@ -48,14 +48,14 @@ const char *detail::debugType(const char
 }
 
 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();
 }
 

Modified: clang-tools-extra/trunk/clangd/Protocol.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Protocol.cpp (original)
+++ clang-tools-extra/trunk/clangd/Protocol.cpp Mon Jan  7 07:45:19 2019
@@ -24,14 +24,14 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
 char LSPError::ID;
 
-URIForFile URIForFile::canonicalize(StringRef AbsPath, StringRef TUPath) {
-  assert(sys::path::is_absolute(AbsPath) && "the path is relative");
+URIForFile URIForFile::canonicalize(llvm::StringRef AbsPath,
+                                    llvm::StringRef TUPath) {
+  assert(llvm::sys::path::is_absolute(AbsPath) && "the path is relative");
   auto Resolved = URI::resolvePath(AbsPath, TUPath);
   if (!Resolved) {
     elog("URIForFile: failed to resolve path {0} with TU path {1}: "
@@ -42,14 +42,15 @@ URIForFile URIForFile::canonicalize(Stri
   return URIForFile(std::move(*Resolved));
 }
 
-Expected<URIForFile> URIForFile::fromURI(const URI &U, StringRef HintPath) {
+llvm::Expected<URIForFile> URIForFile::fromURI(const URI &U,
+                                               llvm::StringRef HintPath) {
   auto Resolved = URI::resolve(U, HintPath);
   if (!Resolved)
     return Resolved.takeError();
   return URIForFile(std::move(*Resolved));
 }
 
-bool fromJSON(const json::Value &E, URIForFile &R) {
+bool fromJSON(const llvm::json::Value &E, URIForFile &R) {
   if (auto S = E.getAsString()) {
     auto Parsed = URI::parse(*S);
     if (!Parsed) {
@@ -73,89 +74,89 @@ bool fromJSON(const json::Value &E, URIF
   return false;
 }
 
-json::Value toJSON(const URIForFile &U) { return U.uri(); }
+llvm::json::Value toJSON(const URIForFile &U) { return U.uri(); }
 
-raw_ostream &operator<<(raw_ostream &OS, const URIForFile &U) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const URIForFile &U) {
   return OS << U.uri();
 }
 
-json::Value toJSON(const TextDocumentIdentifier &R) {
-  return json::Object{{"uri", R.uri}};
+llvm::json::Value toJSON(const TextDocumentIdentifier &R) {
+  return llvm::json::Object{{"uri", R.uri}};
 }
 
-bool fromJSON(const json::Value &Params, TextDocumentIdentifier &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, TextDocumentIdentifier &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("uri", R.uri);
 }
 
-bool fromJSON(const json::Value &Params, Position &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, Position &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("line", R.line) && O.map("character", R.character);
 }
 
-json::Value toJSON(const Position &P) {
-  return json::Object{
+llvm::json::Value toJSON(const Position &P) {
+  return llvm::json::Object{
       {"line", P.line},
       {"character", P.character},
   };
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const Position &P) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Position &P) {
   return OS << P.line << ':' << P.character;
 }
 
-bool fromJSON(const json::Value &Params, Range &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, Range &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("start", R.start) && O.map("end", R.end);
 }
 
-json::Value toJSON(const Range &P) {
-  return json::Object{
+llvm::json::Value toJSON(const Range &P) {
+  return llvm::json::Object{
       {"start", P.start},
       {"end", P.end},
   };
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const Range &R) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Range &R) {
   return OS << R.start << '-' << R.end;
 }
 
-json::Value toJSON(const Location &P) {
-  return json::Object{
+llvm::json::Value toJSON(const Location &P) {
+  return llvm::json::Object{
       {"uri", P.uri},
       {"range", P.range},
   };
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const Location &L) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Location &L) {
   return OS << L.range << '@' << L.uri;
 }
 
-bool fromJSON(const json::Value &Params, TextDocumentItem &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, TextDocumentItem &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("uri", R.uri) && O.map("languageId", R.languageId) &&
          O.map("version", R.version) && O.map("text", R.text);
 }
 
-bool fromJSON(const json::Value &Params, TextEdit &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, TextEdit &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("range", R.range) && O.map("newText", R.newText);
 }
 
-json::Value toJSON(const TextEdit &P) {
-  return json::Object{
+llvm::json::Value toJSON(const TextEdit &P) {
+  return llvm::json::Object{
       {"range", P.range},
       {"newText", P.newText},
   };
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const TextEdit &TE) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const TextEdit &TE) {
   OS << TE.range << " => \"";
-  printEscapedString(TE.newText, OS);
+  llvm::printEscapedString(TE.newText, OS);
   return OS << '"';
 }
 
-bool fromJSON(const json::Value &E, TraceLevel &Out) {
+bool fromJSON(const llvm::json::Value &E, TraceLevel &Out) {
   if (auto S = E.getAsString()) {
     if (*S == "off") {
       Out = TraceLevel::Off;
@@ -171,7 +172,7 @@ bool fromJSON(const json::Value &E, Trac
   return false;
 }
 
-bool fromJSON(const json::Value &E, SymbolKind &Out) {
+bool fromJSON(const llvm::json::Value &E, SymbolKind &Out) {
   if (auto T = E.getAsInteger()) {
     if (*T < static_cast<int>(SymbolKind::File) ||
         *T > static_cast<int>(SymbolKind::TypeParameter))
@@ -182,7 +183,7 @@ bool fromJSON(const json::Value &E, Symb
   return false;
 }
 
-bool fromJSON(const json::Value &E, SymbolKindBitset &Out) {
+bool fromJSON(const llvm::json::Value &E, SymbolKindBitset &Out) {
   if (auto *A = E.getAsArray()) {
     for (size_t I = 0; I < A->size(); ++I) {
       SymbolKind KindOut;
@@ -212,8 +213,8 @@ SymbolKind adjustKindToCapability(Symbol
   }
 }
 
-bool fromJSON(const json::Value &Params, ClientCapabilities &R) {
-  const json::Object *O = Params.getAsObject();
+bool fromJSON(const llvm::json::Value &Params, ClientCapabilities &R) {
+  const llvm::json::Object *O = Params.getAsObject();
   if (!O)
     return false;
   if (auto *TextDocument = O->getObject("textDocument")) {
@@ -260,8 +261,8 @@ bool fromJSON(const json::Value &Params,
   return true;
 }
 
-bool fromJSON(const json::Value &Params, InitializeParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, InitializeParams &R) {
+  llvm::json::ObjectMapper O(Params);
   if (!O)
     return false;
   // We deliberately don't fail if we can't parse individual fields.
@@ -275,24 +276,24 @@ bool fromJSON(const json::Value &Params,
   return true;
 }
 
-bool fromJSON(const json::Value &Params, DidOpenTextDocumentParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DidOpenTextDocumentParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("textDocument", R.textDocument);
 }
 
-bool fromJSON(const json::Value &Params, DidCloseTextDocumentParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DidCloseTextDocumentParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("textDocument", R.textDocument);
 }
 
-bool fromJSON(const json::Value &Params, DidChangeTextDocumentParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DidChangeTextDocumentParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("textDocument", R.textDocument) &&
          O.map("contentChanges", R.contentChanges) &&
          O.map("wantDiagnostics", R.wantDiagnostics);
 }
 
-bool fromJSON(const json::Value &E, FileChangeType &Out) {
+bool fromJSON(const llvm::json::Value &E, FileChangeType &Out) {
   if (auto T = E.getAsInteger()) {
     if (*T < static_cast<int>(FileChangeType::Created) ||
         *T > static_cast<int>(FileChangeType::Deleted))
@@ -303,61 +304,64 @@ bool fromJSON(const json::Value &E, File
   return false;
 }
 
-bool fromJSON(const json::Value &Params, FileEvent &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, FileEvent &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("uri", R.uri) && O.map("type", R.type);
 }
 
-bool fromJSON(const json::Value &Params, DidChangeWatchedFilesParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DidChangeWatchedFilesParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("changes", R.changes);
 }
 
-bool fromJSON(const json::Value &Params, TextDocumentContentChangeEvent &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params,
+              TextDocumentContentChangeEvent &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("range", R.range) && O.map("rangeLength", R.rangeLength) &&
          O.map("text", R.text);
 }
 
-bool fromJSON(const json::Value &Params, FormattingOptions &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, FormattingOptions &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("tabSize", R.tabSize) &&
          O.map("insertSpaces", R.insertSpaces);
 }
 
-json::Value toJSON(const FormattingOptions &P) {
-  return json::Object{
+llvm::json::Value toJSON(const FormattingOptions &P) {
+  return llvm::json::Object{
       {"tabSize", P.tabSize},
       {"insertSpaces", P.insertSpaces},
   };
 }
 
-bool fromJSON(const json::Value &Params, DocumentRangeFormattingParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params,
+              DocumentRangeFormattingParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("textDocument", R.textDocument) &&
          O.map("range", R.range) && O.map("options", R.options);
 }
 
-bool fromJSON(const json::Value &Params, DocumentOnTypeFormattingParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params,
+              DocumentOnTypeFormattingParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("textDocument", R.textDocument) &&
          O.map("position", R.position) && O.map("ch", R.ch) &&
          O.map("options", R.options);
 }
 
-bool fromJSON(const json::Value &Params, DocumentFormattingParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DocumentFormattingParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("textDocument", R.textDocument) &&
          O.map("options", R.options);
 }
 
-bool fromJSON(const json::Value &Params, DocumentSymbolParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, DocumentSymbolParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("textDocument", R.textDocument);
 }
 
-json::Value toJSON(const Diagnostic &D) {
-  json::Object Diag{
+llvm::json::Value toJSON(const Diagnostic &D) {
+  llvm::json::Object Diag{
       {"range", D.range},
       {"severity", D.severity},
       {"message", D.message},
@@ -369,8 +373,8 @@ json::Value toJSON(const Diagnostic &D)
   return std::move(Diag);
 }
 
-bool fromJSON(const json::Value &Params, Diagnostic &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, Diagnostic &R) {
+  llvm::json::ObjectMapper O(Params);
   if (!O || !O.map("range", R.range) || !O.map("message", R.message))
     return false;
   O.map("severity", R.severity);
@@ -378,12 +382,12 @@ bool fromJSON(const json::Value &Params,
   return true;
 }
 
-bool fromJSON(const json::Value &Params, CodeActionContext &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, CodeActionContext &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("diagnostics", R.diagnostics);
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const Diagnostic &D) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diagnostic &D) {
   OS << D.range << " [";
   switch (D.severity) {
   case 1:
@@ -405,21 +409,21 @@ raw_ostream &operator<<(raw_ostream &OS,
   return OS << '(' << D.severity << "): " << D.message << "]";
 }
 
-bool fromJSON(const json::Value &Params, CodeActionParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, CodeActionParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("textDocument", R.textDocument) &&
          O.map("range", R.range) && O.map("context", R.context);
 }
 
-bool fromJSON(const json::Value &Params, WorkspaceEdit &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, WorkspaceEdit &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("changes", R.changes);
 }
 
-const StringLiteral ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND =
+const llvm::StringLiteral ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND =
     "clangd.applyFix";
-bool fromJSON(const json::Value &Params, ExecuteCommandParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, ExecuteCommandParams &R) {
+  llvm::json::ObjectMapper O(Params);
   if (!O || !O.map("command", R.command))
     return false;
 
@@ -431,8 +435,8 @@ bool fromJSON(const json::Value &Params,
   return false; // Unrecognized command.
 }
 
-json::Value toJSON(const SymbolInformation &P) {
-  return json::Object{
+llvm::json::Value toJSON(const SymbolInformation &P) {
+  return llvm::json::Object{
       {"name", P.name},
       {"kind", static_cast<int>(P.kind)},
       {"location", P.location},
@@ -440,7 +444,8 @@ json::Value toJSON(const SymbolInformati
   };
 }
 
-raw_ostream &operator<<(raw_ostream &O, const SymbolInformation &SI) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
+                              const SymbolInformation &SI) {
   O << SI.containerName << "::" << SI.name << " - " << toJSON(SI);
   return O;
 }
@@ -451,10 +456,10 @@ bool operator==(const SymbolDetails &LHS
 }
 
 llvm::json::Value toJSON(const SymbolDetails &P) {
-  json::Object result{{"name", llvm::json::Value(nullptr)},
-                      {"containerName", llvm::json::Value(nullptr)},
-                      {"usr", llvm::json::Value(nullptr)},
-                      {"id", llvm::json::Value(nullptr)}};
+  llvm::json::Object result{{"name", llvm::json::Value(nullptr)},
+                            {"containerName", llvm::json::Value(nullptr)},
+                            {"usr", llvm::json::Value(nullptr)},
+                            {"id", llvm::json::Value(nullptr)}};
 
   if (!P.name.empty())
     result["name"] = P.name;
@@ -469,13 +474,13 @@ llvm::json::Value toJSON(const SymbolDet
     result["id"] = P.ID.getValue().str();
 
   // Older clang cannot compile 'return Result', even though it is legal.
-  return json::Value(std::move(result));
+  return llvm::json::Value(std::move(result));
 }
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const SymbolDetails &S) {
   if (!S.containerName.empty()) {
     O << S.containerName;
-    StringRef ContNameRef;
+    llvm::StringRef ContNameRef;
     if (!ContNameRef.endswith("::")) {
       O << " ";
     }
@@ -484,26 +489,26 @@ llvm::raw_ostream &operator<<(llvm::raw_
   return O;
 }
 
-bool fromJSON(const json::Value &Params, WorkspaceSymbolParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, WorkspaceSymbolParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("query", R.query);
 }
 
-json::Value toJSON(const Command &C) {
-  auto Cmd = json::Object{{"title", C.title}, {"command", C.command}};
+llvm::json::Value toJSON(const Command &C) {
+  auto Cmd = llvm::json::Object{{"title", C.title}, {"command", C.command}};
   if (C.workspaceEdit)
     Cmd["arguments"] = {*C.workspaceEdit};
   return std::move(Cmd);
 }
 
-const StringLiteral CodeAction::QUICKFIX_KIND = "quickfix";
+const llvm::StringLiteral CodeAction::QUICKFIX_KIND = "quickfix";
 
-json::Value toJSON(const CodeAction &CA) {
-  auto CodeAction = json::Object{{"title", CA.title}};
+llvm::json::Value toJSON(const CodeAction &CA) {
+  auto CodeAction = llvm::json::Object{{"title", CA.title}};
   if (CA.kind)
     CodeAction["kind"] = *CA.kind;
   if (CA.diagnostics)
-    CodeAction["diagnostics"] = json::Array(*CA.diagnostics);
+    CodeAction["diagnostics"] = llvm::json::Array(*CA.diagnostics);
   if (CA.edit)
     CodeAction["edit"] = *CA.edit;
   if (CA.command)
@@ -511,15 +516,15 @@ json::Value toJSON(const CodeAction &CA)
   return std::move(CodeAction);
 }
 
-raw_ostream &operator<<(raw_ostream &O, const DocumentSymbol &S) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const DocumentSymbol &S) {
   return O << S.name << " - " << toJSON(S);
 }
 
-json::Value toJSON(const DocumentSymbol &S) {
-  json::Object Result{{"name", S.name},
-                      {"kind", static_cast<int>(S.kind)},
-                      {"range", S.range},
-                      {"selectionRange", S.selectionRange}};
+llvm::json::Value toJSON(const DocumentSymbol &S) {
+  llvm::json::Object Result{{"name", S.name},
+                            {"kind", static_cast<int>(S.kind)},
+                            {"range", S.range},
+                            {"selectionRange", S.selectionRange}};
 
   if (!S.detail.empty())
     Result["detail"] = S.detail;
@@ -528,30 +533,30 @@ json::Value toJSON(const DocumentSymbol
   if (S.deprecated)
     Result["deprecated"] = true;
   // Older gcc cannot compile 'return Result', even though it is legal.
-  return json::Value(std::move(Result));
+  return llvm::json::Value(std::move(Result));
 }
 
-json::Value toJSON(const WorkspaceEdit &WE) {
+llvm::json::Value toJSON(const WorkspaceEdit &WE) {
   if (!WE.changes)
-    return json::Object{};
-  json::Object FileChanges;
+    return llvm::json::Object{};
+  llvm::json::Object FileChanges;
   for (auto &Change : *WE.changes)
-    FileChanges[Change.first] = json::Array(Change.second);
-  return json::Object{{"changes", std::move(FileChanges)}};
+    FileChanges[Change.first] = llvm::json::Array(Change.second);
+  return llvm::json::Object{{"changes", std::move(FileChanges)}};
 }
 
-json::Value toJSON(const ApplyWorkspaceEditParams &Params) {
-  return json::Object{{"edit", Params.edit}};
+llvm::json::Value toJSON(const ApplyWorkspaceEditParams &Params) {
+  return llvm::json::Object{{"edit", Params.edit}};
 }
 
-bool fromJSON(const json::Value &Params, TextDocumentPositionParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, TextDocumentPositionParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("textDocument", R.textDocument) &&
          O.map("position", R.position);
 }
 
 bool fromJSON(const llvm::json::Value &Params, CompletionContext &R) {
-  json::ObjectMapper O(Params);
+  llvm::json::ObjectMapper O(Params);
   if (!O)
     return false;
 
@@ -573,7 +578,7 @@ bool fromJSON(const llvm::json::Value &P
   return true;
 }
 
-static StringRef toTextKind(MarkupKind Kind) {
+static llvm::StringRef toTextKind(MarkupKind Kind) {
   switch (Kind) {
   case MarkupKind::PlainText:
     return "plaintext";
@@ -583,18 +588,18 @@ static StringRef toTextKind(MarkupKind K
   llvm_unreachable("Invalid MarkupKind");
 }
 
-json::Value toJSON(const MarkupContent &MC) {
+llvm::json::Value toJSON(const MarkupContent &MC) {
   if (MC.value.empty())
     return nullptr;
 
-  return json::Object{
+  return llvm::json::Object{
       {"kind", toTextKind(MC.kind)},
       {"value", MC.value},
   };
 }
 
-json::Value toJSON(const Hover &H) {
-  json::Object Result{{"contents", toJSON(H.contents)}};
+llvm::json::Value toJSON(const Hover &H) {
+  llvm::json::Object Result{{"contents", toJSON(H.contents)}};
 
   if (H.range.hasValue())
     Result["range"] = toJSON(*H.range);
@@ -602,7 +607,7 @@ json::Value toJSON(const Hover &H) {
   return std::move(Result);
 }
 
-bool fromJSON(const json::Value &E, CompletionItemKind &Out) {
+bool fromJSON(const llvm::json::Value &E, CompletionItemKind &Out) {
   if (auto T = E.getAsInteger()) {
     if (*T < static_cast<int>(CompletionItemKind::Text) ||
         *T > static_cast<int>(CompletionItemKind::TypeParameter))
@@ -635,7 +640,7 @@ adjustKindToCapability(CompletionItemKin
   }
 }
 
-bool fromJSON(const json::Value &E, CompletionItemKindBitset &Out) {
+bool fromJSON(const llvm::json::Value &E, CompletionItemKindBitset &Out) {
   if (auto *A = E.getAsArray()) {
     for (size_t I = 0; I < A->size(); ++I) {
       CompletionItemKind KindOut;
@@ -647,9 +652,9 @@ bool fromJSON(const json::Value &E, Comp
   return false;
 }
 
-json::Value toJSON(const CompletionItem &CI) {
+llvm::json::Value toJSON(const CompletionItem &CI) {
   assert(!CI.label.empty() && "completion item label is required");
-  json::Object Result{{"label", CI.label}};
+  llvm::json::Object Result{{"label", CI.label}};
   if (CI.kind != CompletionItemKind::Missing)
     Result["kind"] = static_cast<int>(CI.kind);
   if (!CI.detail.empty())
@@ -667,13 +672,13 @@ json::Value toJSON(const CompletionItem
   if (CI.textEdit)
     Result["textEdit"] = *CI.textEdit;
   if (!CI.additionalTextEdits.empty())
-    Result["additionalTextEdits"] = json::Array(CI.additionalTextEdits);
+    Result["additionalTextEdits"] = llvm::json::Array(CI.additionalTextEdits);
   if (CI.deprecated)
     Result["deprecated"] = CI.deprecated;
   return std::move(Result);
 }
 
-raw_ostream &operator<<(raw_ostream &O, const CompletionItem &I) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const CompletionItem &I) {
   O << I.label << " - " << toJSON(I);
   return O;
 }
@@ -683,70 +688,72 @@ bool operator<(const CompletionItem &L,
          (R.sortText.empty() ? R.label : R.sortText);
 }
 
-json::Value toJSON(const CompletionList &L) {
-  return json::Object{
+llvm::json::Value toJSON(const CompletionList &L) {
+  return llvm::json::Object{
       {"isIncomplete", L.isIncomplete},
-      {"items", json::Array(L.items)},
+      {"items", llvm::json::Array(L.items)},
   };
 }
 
-json::Value toJSON(const ParameterInformation &PI) {
+llvm::json::Value toJSON(const ParameterInformation &PI) {
   assert(!PI.label.empty() && "parameter information label is required");
-  json::Object Result{{"label", PI.label}};
+  llvm::json::Object Result{{"label", PI.label}};
   if (!PI.documentation.empty())
     Result["documentation"] = PI.documentation;
   return std::move(Result);
 }
 
-json::Value toJSON(const SignatureInformation &SI) {
+llvm::json::Value toJSON(const SignatureInformation &SI) {
   assert(!SI.label.empty() && "signature information label is required");
-  json::Object Result{
+  llvm::json::Object Result{
       {"label", SI.label},
-      {"parameters", json::Array(SI.parameters)},
+      {"parameters", llvm::json::Array(SI.parameters)},
   };
   if (!SI.documentation.empty())
     Result["documentation"] = SI.documentation;
   return std::move(Result);
 }
 
-raw_ostream &operator<<(raw_ostream &O, const SignatureInformation &I) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
+                              const SignatureInformation &I) {
   O << I.label << " - " << toJSON(I);
   return O;
 }
 
-json::Value toJSON(const SignatureHelp &SH) {
+llvm::json::Value toJSON(const SignatureHelp &SH) {
   assert(SH.activeSignature >= 0 &&
          "Unexpected negative value for number of active signatures.");
   assert(SH.activeParameter >= 0 &&
          "Unexpected negative value for active parameter index");
-  return json::Object{
+  return llvm::json::Object{
       {"activeSignature", SH.activeSignature},
       {"activeParameter", SH.activeParameter},
-      {"signatures", json::Array(SH.signatures)},
+      {"signatures", llvm::json::Array(SH.signatures)},
   };
 }
 
-bool fromJSON(const json::Value &Params, RenameParams &R) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, RenameParams &R) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("textDocument", R.textDocument) &&
          O.map("position", R.position) && O.map("newName", R.newName);
 }
 
-json::Value toJSON(const DocumentHighlight &DH) {
-  return json::Object{
+llvm::json::Value toJSON(const DocumentHighlight &DH) {
+  return llvm::json::Object{
       {"range", toJSON(DH.range)},
       {"kind", static_cast<int>(DH.kind)},
   };
 }
 
 llvm::json::Value toJSON(const FileStatus &FStatus) {
-  return json::Object{
+  return llvm::json::Object{
       {"uri", FStatus.uri},
       {"state", FStatus.state},
   };
 }
 
-raw_ostream &operator<<(raw_ostream &O, const DocumentHighlight &V) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
+                              const DocumentHighlight &V) {
   O << V.range;
   if (V.kind == DocumentHighlightKind::Read)
     O << "(r)";
@@ -755,27 +762,29 @@ raw_ostream &operator<<(raw_ostream &O,
   return O;
 }
 
-bool fromJSON(const json::Value &Params, DidChangeConfigurationParams &CCP) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params,
+              DidChangeConfigurationParams &CCP) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("settings", CCP.settings);
 }
 
-bool fromJSON(const json::Value &Params, ClangdCompileCommand &CDbUpdate) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params,
+              ClangdCompileCommand &CDbUpdate) {
+  llvm::json::ObjectMapper O(Params);
   return O && O.map("workingDirectory", CDbUpdate.workingDirectory) &&
          O.map("compilationCommand", CDbUpdate.compilationCommand);
 }
 
-bool fromJSON(const json::Value &Params, ConfigurationSettings &S) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, ConfigurationSettings &S) {
+  llvm::json::ObjectMapper O(Params);
   if (!O)
     return true; // 'any' type in LSP.
   O.map("compilationDatabaseChanges", S.compilationDatabaseChanges);
   return true;
 }
 
-bool fromJSON(const json::Value &Params, InitializationOptions &Opts) {
-  json::ObjectMapper O(Params);
+bool fromJSON(const llvm::json::Value &Params, InitializationOptions &Opts) {
+  llvm::json::ObjectMapper O(Params);
   if (!O)
     return true; // 'any' type in LSP.
 
@@ -786,7 +795,7 @@ bool fromJSON(const json::Value &Params,
   return true;
 }
 
-bool fromJSON(const json::Value &Params, ReferenceParams &R) {
+bool fromJSON(const llvm::json::Value &Params, ReferenceParams &R) {
   TextDocumentPositionParams &Base = R;
   return fromJSON(Params, Base);
 }

Modified: clang-tools-extra/trunk/clangd/Quality.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Quality.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Quality.cpp (original)
+++ clang-tools-extra/trunk/clangd/Quality.cpp Mon Jan  7 07:45:19 2019
@@ -31,10 +31,9 @@
 #include <algorithm>
 #include <cmath>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
-static bool isReserved(StringRef Name) {
+static bool isReserved(llvm::StringRef Name) {
   // FIXME: Should we exclude _Bool and others recognized by the standard?
   return Name.size() >= 2 && Name[0] == '_' &&
          (isUppercase(Name[1]) || Name[1] == '_');
@@ -249,12 +248,13 @@ float SymbolQualitySignals::evaluate() c
   return Score;
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const SymbolQualitySignals &S) {
-  OS << formatv("=== Symbol quality: {0}\n", S.evaluate());
-  OS << formatv("\tReferences: {0}\n", S.References);
-  OS << formatv("\tDeprecated: {0}\n", S.Deprecated);
-  OS << formatv("\tReserved name: {0}\n", S.ReservedName);
-  OS << formatv("\tCategory: {0}\n", static_cast<int>(S.Category));
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+                              const SymbolQualitySignals &S) {
+  OS << llvm::formatv("=== Symbol quality: {0}\n", S.evaluate());
+  OS << llvm::formatv("\tReferences: {0}\n", S.References);
+  OS << llvm::formatv("\tDeprecated: {0}\n", S.Deprecated);
+  OS << llvm::formatv("\tReserved name: {0}\n", S.ReservedName);
+  OS << llvm::formatv("\tCategory: {0}\n", static_cast<int>(S.Category));
   return OS;
 }
 
@@ -317,7 +317,7 @@ void SymbolRelevanceSignals::merge(const
   NeedsFixIts = !SemaCCResult.FixIts.empty();
 }
 
-static std::pair<float, unsigned> uriProximity(StringRef SymbolURI,
+static std::pair<float, unsigned> uriProximity(llvm::StringRef SymbolURI,
                                                URIDistance *D) {
   if (!D || SymbolURI.empty())
     return {0.f, 0u};
@@ -327,7 +327,7 @@ static std::pair<float, unsigned> uriPro
 }
 
 static float scopeBoost(ScopeDistance &Distance,
-                        Optional<StringRef> SymbolScope) {
+                        llvm::Optional<llvm::StringRef> SymbolScope) {
   if (!SymbolScope)
     return 1;
   auto D = Distance.distance(*SymbolScope);
@@ -397,33 +397,34 @@ float SymbolRelevanceSignals::evaluate()
   return Score;
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const SymbolRelevanceSignals &S) {
-  OS << formatv("=== Symbol relevance: {0}\n", S.evaluate());
-  OS << formatv("\tName match: {0}\n", S.NameMatch);
-  OS << formatv("\tForbidden: {0}\n", S.Forbidden);
-  OS << formatv("\tNeedsFixIts: {0}\n", S.NeedsFixIts);
-  OS << formatv("\tIsInstanceMember: {0}\n", S.IsInstanceMember);
-  OS << formatv("\tContext: {0}\n", getCompletionKindString(S.Context));
-  OS << formatv("\tQuery type: {0}\n", static_cast<int>(S.Query));
-  OS << formatv("\tScope: {0}\n", static_cast<int>(S.Scope));
-
-  OS << formatv("\tSymbol URI: {0}\n", S.SymbolURI);
-  OS << formatv("\tSymbol scope: {0}\n",
-                S.SymbolScope ? *S.SymbolScope : "<None>");
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+                              const SymbolRelevanceSignals &S) {
+  OS << llvm::formatv("=== Symbol relevance: {0}\n", S.evaluate());
+  OS << llvm::formatv("\tName match: {0}\n", S.NameMatch);
+  OS << llvm::formatv("\tForbidden: {0}\n", S.Forbidden);
+  OS << llvm::formatv("\tNeedsFixIts: {0}\n", S.NeedsFixIts);
+  OS << llvm::formatv("\tIsInstanceMember: {0}\n", S.IsInstanceMember);
+  OS << llvm::formatv("\tContext: {0}\n", getCompletionKindString(S.Context));
+  OS << llvm::formatv("\tQuery type: {0}\n", static_cast<int>(S.Query));
+  OS << llvm::formatv("\tScope: {0}\n", static_cast<int>(S.Scope));
+
+  OS << llvm::formatv("\tSymbol URI: {0}\n", S.SymbolURI);
+  OS << llvm::formatv("\tSymbol scope: {0}\n",
+                      S.SymbolScope ? *S.SymbolScope : "<None>");
 
   if (S.FileProximityMatch) {
     auto Score = uriProximity(S.SymbolURI, S.FileProximityMatch);
-    OS << formatv("\tIndex URI proximity: {0} (distance={1})\n", Score.first,
-                  Score.second);
+    OS << llvm::formatv("\tIndex URI proximity: {0} (distance={1})\n",
+                        Score.first, Score.second);
   }
-  OS << formatv("\tSema file proximity: {0}\n", S.SemaFileProximityScore);
+  OS << llvm::formatv("\tSema file proximity: {0}\n", S.SemaFileProximityScore);
 
-  OS << formatv("\tSema says in scope: {0}\n", S.SemaSaysInScope);
+  OS << llvm::formatv("\tSema says in scope: {0}\n", S.SemaSaysInScope);
   if (S.ScopeProximityMatch)
-    OS << formatv("\tIndex scope boost: {0}\n",
-                  scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));
+    OS << llvm::formatv("\tIndex scope boost: {0}\n",
+                        scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));
 
-  OS << formatv(
+  OS << llvm::formatv(
       "\tType matched preferred: {0} (Context type: {1}, Symbol type: {2}\n",
       S.TypeMatchesPreferred, S.HadContextType, S.HadSymbolType);
 
@@ -441,33 +442,34 @@ static uint32_t encodeFloat(float F) {
   constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);
 
   // Get the bits of the float. Endianness is the same as for integers.
-  uint32_t U = FloatToBits(F);
+  uint32_t U = llvm::FloatToBits(F);
   // IEEE 754 floats compare like sign-magnitude integers.
   if (U & TopBit)    // Negative float.
     return 0 - U;    // Map onto the low half of integers, order reversed.
   return U + TopBit; // Positive floats map onto the high half of integers.
 }
 
-std::string sortText(float Score, StringRef Name) {
+std::string sortText(float Score, llvm::StringRef Name) {
   // We convert -Score to an integer, and hex-encode for readability.
   // Example: [0.5, "foo"] -> "41000000foo"
   std::string S;
-  raw_string_ostream OS(S);
-  write_hex(OS, encodeFloat(-Score), HexPrintStyle::Lower,
-            /*Width=*/2 * sizeof(Score));
+  llvm::raw_string_ostream OS(S);
+  llvm::write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower,
+                  /*Width=*/2 * sizeof(Score));
   OS << Name;
   OS.flush();
   return S;
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const SignatureQualitySignals &S) {
-  OS << formatv("=== Signature Quality:\n");
-  OS << formatv("\tNumber of parameters: {0}\n", S.NumberOfParameters);
-  OS << formatv("\tNumber of optional parameters: {0}\n",
-                S.NumberOfOptionalParameters);
-  OS << formatv("\tContains active parameter: {0}\n",
-                S.ContainsActiveParameter);
-  OS << formatv("\tKind: {0}\n", S.Kind);
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+                              const SignatureQualitySignals &S) {
+  OS << llvm::formatv("=== Signature Quality:\n");
+  OS << llvm::formatv("\tNumber of parameters: {0}\n", S.NumberOfParameters);
+  OS << llvm::formatv("\tNumber of optional parameters: {0}\n",
+                      S.NumberOfOptionalParameters);
+  OS << llvm::formatv("\tContains active parameter: {0}\n",
+                      S.ContainsActiveParameter);
+  OS << llvm::formatv("\tKind: {0}\n", S.Kind);
   return OS;
 }
 

Modified: clang-tools-extra/trunk/clangd/RIFF.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/RIFF.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/RIFF.cpp (original)
+++ clang-tools-extra/trunk/clangd/RIFF.cpp Mon Jan  7 07:45:19 2019
@@ -10,22 +10,21 @@
 #include "RIFF.h"
 #include "llvm/Support/Endian.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace riff {
 
-static Error makeError(const char *Msg) {
-  return createStringError(inconvertibleErrorCode(), Msg);
+static llvm::Error makeError(const char *Msg) {
+  return llvm::createStringError(llvm::inconvertibleErrorCode(), Msg);
 }
 
-Expected<Chunk> readChunk(StringRef &Stream) {
+llvm::Expected<Chunk> readChunk(llvm::StringRef &Stream) {
   if (Stream.size() < 8)
     return makeError("incomplete chunk header");
   Chunk C;
   std::copy(Stream.begin(), Stream.begin() + 4, C.ID.begin());
   Stream = Stream.drop_front(4);
-  uint32_t Len = support::endian::read32le(Stream.take_front(4).begin());
+  uint32_t Len = llvm::support::endian::read32le(Stream.take_front(4).begin());
   Stream = Stream.drop_front(4);
   if (Stream.size() < Len)
     return makeError("truncated chunk");
@@ -39,10 +38,10 @@ Expected<Chunk> readChunk(StringRef &Str
   return std::move(C);
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const Chunk &C) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Chunk &C) {
   OS.write(C.ID.data(), C.ID.size());
   char Size[4];
-  support::endian::write32le(Size, C.Data.size());
+  llvm::support::endian::write32le(Size, C.Data.size());
   OS.write(Size, sizeof(Size));
   OS << C.Data;
   if (C.Data.size() % 2)
@@ -50,7 +49,7 @@ raw_ostream &operator<<(raw_ostream &OS,
   return OS;
 }
 
-Expected<File> readFile(StringRef Stream) {
+llvm::Expected<File> readFile(llvm::StringRef Stream) {
   auto RIFF = readChunk(Stream);
   if (!RIFF)
     return RIFF.takeError();
@@ -60,7 +59,7 @@ Expected<File> readFile(StringRef Stream
     return makeError("RIFF chunk too short");
   File F;
   std::copy(RIFF->Data.begin(), RIFF->Data.begin() + 4, F.Type.begin());
-  for (StringRef Body = RIFF->Data.drop_front(4); !Body.empty();)
+  for (llvm::StringRef Body = RIFF->Data.drop_front(4); !Body.empty();)
     if (auto Chunk = readChunk(Body)) {
       F.Chunks.push_back(*Chunk);
     } else
@@ -68,14 +67,14 @@ Expected<File> readFile(StringRef Stream
   return std::move(F);
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const File &F) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const File &F) {
   // To avoid copies, we serialize the outer RIFF chunk "by hand".
   size_t DataLen = 4; // Predict length of RIFF chunk data.
   for (const auto &C : F.Chunks)
     DataLen += 4 + 4 + C.Data.size() + (C.Data.size() % 2);
   OS << "RIFF";
   char Size[4];
-  support::endian::write32le(Size, DataLen);
+  llvm::support::endian::write32le(Size, DataLen);
   OS.write(Size, sizeof(Size));
   OS.write(F.Type.data(), F.Type.size());
   for (const auto &C : F.Chunks)

Modified: clang-tools-extra/trunk/clangd/SourceCode.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/SourceCode.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/SourceCode.cpp (original)
+++ clang-tools-extra/trunk/clangd/SourceCode.cpp Mon Jan  7 07:45:19 2019
@@ -16,7 +16,6 @@
 #include "llvm/Support/Error.h"
 #include "llvm/Support/Path.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -27,7 +26,7 @@ namespace clangd {
 // invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true.
 // Returns true if CB returned true, false if we hit the end of string.
 template <typename Callback>
-static bool iterateCodepoints(StringRef U8, const Callback &CB) {
+static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
   for (size_t I = 0; I < U8.size();) {
     unsigned char C = static_cast<unsigned char>(U8[I]);
     if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
@@ -37,7 +36,7 @@ static bool iterateCodepoints(StringRef
       continue;
     }
     // This convenient property of UTF-8 holds for all non-ASCII characters.
-    size_t UTF8Length = countLeadingOnes(C);
+    size_t UTF8Length = llvm::countLeadingOnes(C);
     // 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here.
     // 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug.
     assert((UTF8Length >= 2 && UTF8Length <= 4) &&
@@ -54,7 +53,7 @@ static bool iterateCodepoints(StringRef
 // Returns the offset into the string that matches \p Units UTF-16 code units.
 // Conceptually, this converts to UTF-16, truncates to CodeUnits, converts back
 // to UTF-8, and returns the length in bytes.
-static size_t measureUTF16(StringRef U8, int U16Units, bool &Valid) {
+static size_t measureUTF16(llvm::StringRef U8, int U16Units, bool &Valid) {
   size_t Result = 0;
   Valid = U16Units == 0 || iterateCodepoints(U8, [&](int U8Len, int U16Len) {
             Result += U8Len;
@@ -68,7 +67,7 @@ static size_t measureUTF16(StringRef U8,
 }
 
 // Like most strings in clangd, the input is UTF-8 encoded.
-size_t lspLength(StringRef Code) {
+size_t lspLength(llvm::StringRef Code) {
   // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
   // Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx.
   size_t Count = 0;
@@ -79,47 +78,47 @@ size_t lspLength(StringRef Code) {
   return Count;
 }
 
-Expected<size_t> positionToOffset(StringRef Code, Position P,
-                                  bool AllowColumnsBeyondLineLength) {
+llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
+                                        bool AllowColumnsBeyondLineLength) {
   if (P.line < 0)
-    return make_error<StringError>(
-        formatv("Line value can't be negative ({0})", P.line),
-        errc::invalid_argument);
+    return llvm::make_error<llvm::StringError>(
+        llvm::formatv("Line value can't be negative ({0})", P.line),
+        llvm::errc::invalid_argument);
   if (P.character < 0)
-    return make_error<StringError>(
-        formatv("Character value can't be negative ({0})", P.character),
-        errc::invalid_argument);
+    return llvm::make_error<llvm::StringError>(
+        llvm::formatv("Character value can't be negative ({0})", P.character),
+        llvm::errc::invalid_argument);
   size_t StartOfLine = 0;
   for (int I = 0; I != P.line; ++I) {
     size_t NextNL = Code.find('\n', StartOfLine);
-    if (NextNL == StringRef::npos)
-      return make_error<StringError>(
-          formatv("Line value is out of range ({0})", P.line),
-          errc::invalid_argument);
+    if (NextNL == llvm::StringRef::npos)
+      return llvm::make_error<llvm::StringError>(
+          llvm::formatv("Line value is out of range ({0})", P.line),
+          llvm::errc::invalid_argument);
     StartOfLine = NextNL + 1;
   }
 
   size_t NextNL = Code.find('\n', StartOfLine);
-  if (NextNL == StringRef::npos)
+  if (NextNL == llvm::StringRef::npos)
     NextNL = Code.size();
 
   bool Valid;
   size_t ByteOffsetInLine = measureUTF16(
       Code.substr(StartOfLine, NextNL - StartOfLine), P.character, Valid);
   if (!Valid && !AllowColumnsBeyondLineLength)
-    return make_error<StringError>(
-        formatv("UTF-16 offset {0} is invalid for line {1}", P.character,
-                P.line),
-        errc::invalid_argument);
+    return llvm::make_error<llvm::StringError>(
+        llvm::formatv("UTF-16 offset {0} is invalid for line {1}", P.character,
+                      P.line),
+        llvm::errc::invalid_argument);
   return StartOfLine + ByteOffsetInLine;
 }
 
-Position offsetToPosition(StringRef Code, size_t Offset) {
+Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
   Offset = std::min(Code.size(), Offset);
-  StringRef Before = Code.substr(0, Offset);
+  llvm::StringRef Before = Code.substr(0, Offset);
   int Lines = Before.count('\n');
   size_t PrevNL = Before.rfind('\n');
-  size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
+  size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
   Position Pos;
   Pos.line = Lines;
   Pos.character = lspLength(Before.substr(StartOfLine));
@@ -134,7 +133,7 @@ Position sourceLocToPosition(const Sourc
   Position P;
   P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
   bool Invalid = false;
-  StringRef Code = SM.getBufferData(FID, &Invalid);
+  llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
   if (!Invalid) {
     auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
     auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
@@ -151,31 +150,33 @@ Range halfOpenToRange(const SourceManage
   return {Begin, End};
 }
 
-std::pair<size_t, size_t> offsetToClangLineColumn(StringRef Code,
+std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
                                                   size_t Offset) {
   Offset = std::min(Code.size(), Offset);
-  StringRef Before = Code.substr(0, Offset);
+  llvm::StringRef Before = Code.substr(0, Offset);
   int Lines = Before.count('\n');
   size_t PrevNL = Before.rfind('\n');
-  size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
+  size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
   return {Lines + 1, Offset - StartOfLine + 1};
 }
 
-std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
+std::pair<llvm::StringRef, llvm::StringRef>
+splitQualifiedName(llvm::StringRef QName) {
   size_t Pos = QName.rfind("::");
-  if (Pos == StringRef::npos)
-    return {StringRef(), QName};
+  if (Pos == llvm::StringRef::npos)
+    return {llvm::StringRef(), QName};
   return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
 }
 
-TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R) {
+TextEdit replacementToEdit(llvm::StringRef Code,
+                           const tooling::Replacement &R) {
   Range ReplacementRange = {
       offsetToPosition(Code, R.getOffset()),
       offsetToPosition(Code, R.getOffset() + R.getLength())};
   return {ReplacementRange, R.getReplacementText()};
 }
 
-std::vector<TextEdit> replacementsToEdits(StringRef Code,
+std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
                                           const tooling::Replacements &Repls) {
   std::vector<TextEdit> Edits;
   for (const auto &R : Repls)
@@ -183,13 +184,13 @@ std::vector<TextEdit> replacementsToEdit
   return Edits;
 }
 
-Optional<std::string> getCanonicalPath(const FileEntry *F,
-                                       const SourceManager &SourceMgr) {
+llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
+                                             const SourceManager &SourceMgr) {
   if (!F)
     return None;
 
-  SmallString<128> FilePath = F->getName();
-  if (!sys::path::is_absolute(FilePath)) {
+  llvm::SmallString<128> FilePath = F->getName();
+  if (!llvm::sys::path::is_absolute(FilePath)) {
     if (auto EC =
             SourceMgr.getFileManager().getVirtualFileSystem()->makeAbsolute(
                 FilePath)) {
@@ -211,10 +212,11 @@ Optional<std::string> getCanonicalPath(c
   //  The file path of Symbol is "/project/src/foo.h" instead of
   //  "/tmp/build/foo.h"
   if (const DirectoryEntry *Dir = SourceMgr.getFileManager().getDirectory(
-          sys::path::parent_path(FilePath))) {
-    SmallString<128> RealPath;
-    StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
-    sys::path::append(RealPath, DirName, sys::path::filename(FilePath));
+          llvm::sys::path::parent_path(FilePath))) {
+    llvm::SmallString<128> RealPath;
+    llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
+    llvm::sys::path::append(RealPath, DirName,
+                            llvm::sys::path::filename(FilePath));
     return RealPath.str().str();
   }
 
@@ -235,13 +237,13 @@ bool IsRangeConsecutive(const Range &Lef
          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);

Modified: clang-tools-extra/trunk/clangd/TUScheduler.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/TUScheduler.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/TUScheduler.cpp (original)
+++ clang-tools-extra/trunk/clangd/TUScheduler.cpp Mon Jan  7 07:45:19 2019
@@ -56,7 +56,6 @@
 #include <queue>
 #include <thread>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 using std::chrono::steady_clock;
@@ -67,9 +66,9 @@ class ASTWorker;
 
 static clang::clangd::Key<std::string> kFileBeingProcessed;
 
-Optional<StringRef> TUScheduler::getFileBeingProcessedInContext() {
+llvm::Optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
   if (auto *File = Context::current().get(kFileBeingProcessed))
-    return StringRef(*File);
+    return llvm::StringRef(*File);
   return None;
 }
 
@@ -113,7 +112,7 @@ public:
   /// Returns the cached value for \p K, or llvm::None if the value is not in
   /// the cache anymore. If nullptr was cached for \p K, this function will
   /// return a null unique_ptr wrapped into an optional.
-  Optional<std::unique_ptr<ParsedAST>> take(Key K) {
+  llvm::Optional<std::unique_ptr<ParsedAST>> take(Key K) {
     std::unique_lock<std::mutex> Lock(Mut);
     auto Existing = findByKey(K);
     if (Existing == LRU.end())
@@ -123,7 +122,7 @@ public:
     // GCC 4.8 fails to compile `return V;`, as it tries to call the copy
     // constructor of unique_ptr, so we call the move ctor explicitly to avoid
     // this miscompile.
-    return Optional<std::unique_ptr<ParsedAST>>(std::move(V));
+    return llvm::Optional<std::unique_ptr<ParsedAST>>(std::move(V));
   }
 
 private:
@@ -177,15 +176,16 @@ public:
   ~ASTWorker();
 
   void update(ParseInputs Inputs, WantDiagnostics);
-  void runWithAST(StringRef Name,
-                  unique_function<void(Expected<InputsAndAST>)> Action);
+  void
+  runWithAST(llvm::StringRef Name,
+             llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action);
   bool blockUntilIdle(Deadline Timeout) const;
 
   std::shared_ptr<const PreambleData> getPossiblyStalePreamble() const;
   /// Obtain a preamble reflecting all updates so far. Threadsafe.
   /// It may be delivered immediately, or later on the worker thread.
   void getCurrentPreamble(
-      unique_function<void(std::shared_ptr<const PreambleData>)>);
+      llvm::unique_function<void(std::shared_ptr<const PreambleData>)>);
   /// Wait for the first build of preamble to finish. Preamble itself can be
   /// accessed via getPossiblyStalePreamble(). Note that this function will
   /// return after an unsuccessful build of the preamble too, i.e. result of
@@ -203,8 +203,8 @@ private:
   /// Signal that run() should finish processing pending requests and exit.
   void stop();
   /// Adds a new task to the end of the request queue.
-  void startTask(StringRef Name, unique_function<void()> Task,
-                 Optional<WantDiagnostics> UpdateType);
+  void startTask(llvm::StringRef Name, llvm::unique_function<void()> Task,
+                 llvm::Optional<WantDiagnostics> UpdateType);
   /// Updates the TUStatus and emits it. Only called in the worker thread.
   void emitTUStatus(TUAction FAction,
                     const TUStatus::BuildDetails *Detail = nullptr);
@@ -218,11 +218,11 @@ private:
   bool shouldSkipHeadLocked() const;
 
   struct Request {
-    unique_function<void()> Action;
+    llvm::unique_function<void()> Action;
     std::string Name;
     steady_clock::time_point AddTime;
     Context Ctx;
-    Optional<WantDiagnostics> UpdateType;
+    llvm::Optional<WantDiagnostics> UpdateType;
   };
 
   /// Handles retention of ASTs.
@@ -321,7 +321,7 @@ ASTWorkerHandle ASTWorker::create(PathRe
       FileName, IdleASTs, Barrier, /*RunSync=*/!Tasks, UpdateDebounce,
       std::move(PCHs), StorePreamblesInMemory, Callbacks));
   if (Tasks)
-    Tasks->runAsync("worker:" + sys::path::filename(FileName),
+    Tasks->runAsync("worker:" + llvm::sys::path::filename(FileName),
                     [Worker]() { Worker->run(); });
 
   return ASTWorkerHandle(std::move(Worker));
@@ -350,7 +350,7 @@ ASTWorker::~ASTWorker() {
 }
 
 void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags) {
-  StringRef TaskName = "Update";
+  llvm::StringRef TaskName = "Update";
   auto Task = [=]() mutable {
     // Will be used to check if we can avoid rebuilding the AST.
     bool InputsAreTheSame =
@@ -364,7 +364,7 @@ void ASTWorker::update(ParseInputs Input
     emitTUStatus({TUAction::BuildingPreamble, TaskName});
     log("Updating file {0} with command [{1}] {2}", FileName,
         Inputs.CompileCommand.Directory,
-        join(Inputs.CompileCommand.CommandLine, " "));
+        llvm::join(Inputs.CompileCommand.CommandLine, " "));
     // Rebuild the preamble and the AST.
     std::unique_ptr<CompilerInvocation> Invocation =
         buildCompilerInvocation(Inputs);
@@ -437,9 +437,9 @@ void ASTWorker::update(ParseInputs Input
     }
 
     // Get the AST for diagnostics.
-    Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
+    llvm::Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
     if (!AST) {
-      Optional<ParsedAST> NewAST =
+      llvm::Optional<ParsedAST> NewAST =
           buildAST(FileName, std::move(Invocation), Inputs, NewPreamble, PCHs);
       AST = NewAST ? llvm::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
       if (!(*AST)) { // buildAST fails.
@@ -474,16 +474,17 @@ void ASTWorker::update(ParseInputs Input
 }
 
 void ASTWorker::runWithAST(
-    StringRef Name, unique_function<void(Expected<InputsAndAST>)> Action) {
+    llvm::StringRef Name,
+    llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action) {
   auto Task = [=](decltype(Action) Action) {
     if (isCancelled())
-      return Action(make_error<CancelledError>());
-    Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
+      return Action(llvm::make_error<CancelledError>());
+    llvm::Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
     if (!AST) {
       std::unique_ptr<CompilerInvocation> Invocation =
           buildCompilerInvocation(FileInputs);
       // Try rebuilding the AST.
-      Optional<ParsedAST> NewAST =
+      llvm::Optional<ParsedAST> NewAST =
           Invocation
               ? buildAST(FileName,
                          llvm::make_unique<CompilerInvocation>(*Invocation),
@@ -492,12 +493,12 @@ void ASTWorker::runWithAST(
       AST = NewAST ? llvm::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
     }
     // Make sure we put the AST back into the LRU cache.
-    auto _ = make_scope_exit(
+    auto _ = llvm::make_scope_exit(
         [&AST, this]() { IdleASTs.put(this, std::move(*AST)); });
     // Run the user-provided action.
     if (!*AST)
-      return Action(
-          make_error<StringError>("invalid AST", errc::invalid_argument));
+      return Action(llvm::make_error<llvm::StringError>(
+          "invalid AST", llvm::errc::invalid_argument));
     Action(InputsAndAST{FileInputs, **AST});
   };
   startTask(Name, Bind(Task, std::move(Action)),
@@ -511,7 +512,7 @@ ASTWorker::getPossiblyStalePreamble() co
 }
 
 void ASTWorker::getCurrentPreamble(
-    unique_function<void(std::shared_ptr<const PreambleData>)> Callback) {
+    llvm::unique_function<void(std::shared_ptr<const PreambleData>)> Callback) {
   // We could just call startTask() to throw the read on the queue, knowing
   // it will run after any updates. But we know this task is cheap, so to
   // improve latency we cheat: insert it on the queue after the last update.
@@ -565,11 +566,12 @@ void ASTWorker::stop() {
   RequestsCV.notify_all();
 }
 
-void ASTWorker::startTask(StringRef Name, unique_function<void()> Task,
-                          Optional<WantDiagnostics> UpdateType) {
+void ASTWorker::startTask(llvm::StringRef Name,
+                          llvm::unique_function<void()> Task,
+                          llvm::Optional<WantDiagnostics> UpdateType) {
   if (RunSync) {
     assert(!Done && "running a task after stop()");
-    trace::Span Tracer(Name + ":" + sys::path::filename(FileName));
+    trace::Span Tracer(Name + ":" + llvm::sys::path::filename(FileName));
     Task();
     return;
   }
@@ -611,8 +613,8 @@ void ASTWorker::run() {
         }
 
         // Tracing: we have a next request, attribute this sleep to it.
-        Optional<WithContext> Ctx;
-        Optional<trace::Span> Tracer;
+        llvm::Optional<WithContext> Ctx;
+        llvm::Optional<trace::Span> Tracer;
         if (!Requests.empty()) {
           Ctx.emplace(Requests.front().Ctx.clone());
           Tracer.emplace("Debounce");
@@ -734,7 +736,7 @@ bool ASTWorker::blockUntilIdle(Deadline
 // are familiar by C++ programmers.
 std::string renderTUAction(const TUAction &Action) {
   std::string Result;
-  raw_string_ostream OS(Result);
+  llvm::raw_string_ostream OS(Result);
   switch (Action.S) {
   case TUAction::Queued:
     OS << "file is queued";
@@ -844,19 +846,20 @@ void TUScheduler::remove(PathRef File) {
          File);
 }
 
-void TUScheduler::run(StringRef Name, unique_function<void()> Action) {
+void TUScheduler::run(llvm::StringRef Name,
+                      llvm::unique_function<void()> Action) {
   if (!PreambleTasks)
     return Action();
   PreambleTasks->runAsync(Name, std::move(Action));
 }
 
 void TUScheduler::runWithAST(
-    StringRef Name, PathRef File,
-    unique_function<void(Expected<InputsAndAST>)> Action) {
+    llvm::StringRef Name, PathRef File,
+    llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action) {
   auto It = Files.find(File);
   if (It == Files.end()) {
-    Action(make_error<LSPError>("trying to get AST for non-added document",
-                                ErrorCode::InvalidParams));
+    Action(llvm::make_error<LSPError>(
+        "trying to get AST for non-added document", ErrorCode::InvalidParams));
     return;
   }
 
@@ -864,12 +867,13 @@ void TUScheduler::runWithAST(
 }
 
 void TUScheduler::runWithPreamble(
-    StringRef Name, PathRef File, PreambleConsistency Consistency,
-    unique_function<void(Expected<InputsAndPreamble>)> Action) {
+    llvm::StringRef Name, PathRef File, PreambleConsistency Consistency,
+    llvm::unique_function<void(llvm::Expected<InputsAndPreamble>)> Action) {
   auto It = Files.find(File);
   if (It == Files.end()) {
-    Action(make_error<LSPError>("trying to get preamble for non-added document",
-                                ErrorCode::InvalidParams));
+    Action(llvm::make_error<LSPError>(
+        "trying to get preamble for non-added document",
+        ErrorCode::InvalidParams));
     return;
   }
 
@@ -921,7 +925,7 @@ void TUScheduler::runWithPreamble(
   };
 
   PreambleTasks->runAsync(
-      "task:" + sys::path::filename(File),
+      "task:" + llvm::sys::path::filename(File),
       Bind(Task, std::string(Name), std::string(File), It->second->Contents,
            It->second->Command,
            Context::current().derive(kFileBeingProcessed, File),

Modified: clang-tools-extra/trunk/clangd/Threading.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Threading.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Threading.cpp (original)
+++ clang-tools-extra/trunk/clangd/Threading.cpp Mon Jan  7 07:45:19 2019
@@ -9,7 +9,6 @@
 #include <pthread.h>
 #endif
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -64,14 +63,14 @@ bool AsyncTaskRunner::wait(Deadline D) c
                       [&] { return InFlightTasks == 0; });
 }
 
-void AsyncTaskRunner::runAsync(const Twine &Name,
-                               unique_function<void()> Action) {
+void AsyncTaskRunner::runAsync(const llvm::Twine &Name,
+                               llvm::unique_function<void()> Action) {
   {
     std::lock_guard<std::mutex> Lock(Mutex);
     ++InFlightTasks;
   }
 
-  auto CleanupTask = make_scope_exit([this]() {
+  auto CleanupTask = llvm::make_scope_exit([this]() {
     std::lock_guard<std::mutex> Lock(Mutex);
     int NewTasksCnt = --InFlightTasks;
     if (NewTasksCnt == 0) {
@@ -83,7 +82,7 @@ void AsyncTaskRunner::runAsync(const Twi
 
   std::thread(
       [](std::string Name, decltype(Action) Action, decltype(CleanupTask)) {
-        set_thread_name(Name);
+        llvm::set_thread_name(Name);
         Action();
         // Make sure function stored by Action is destroyed before CleanupTask
         // is run.
@@ -93,7 +92,7 @@ void AsyncTaskRunner::runAsync(const Twi
       .detach();
 }
 
-Deadline timeoutSeconds(Optional<double> Seconds) {
+Deadline timeoutSeconds(llvm::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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/Trace.cpp (original)
+++ clang-tools-extra/trunk/clangd/Trace.cpp Mon Jan  7 07:45:19 2019
@@ -19,7 +19,6 @@
 #include <atomic>
 #include <mutex>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace trace {
@@ -29,16 +28,16 @@ namespace {
 // Perhaps we should replace this by something that disturbs performance less.
 class JSONTracer : public EventTracer {
 public:
-  JSONTracer(raw_ostream &Out, bool Pretty)
+  JSONTracer(llvm::raw_ostream &Out, bool Pretty)
       : Out(Out), Sep(""), Start(std::chrono::system_clock::now()),
         JSONFormat(Pretty ? "{0:2}" : "{0}") {
     // The displayTimeUnit must be ns to avoid low-precision overlap
     // calculations!
     Out << R"({"displayTimeUnit":"ns","traceEvents":[)"
         << "\n";
-    rawEvent("M", json::Object{
+    rawEvent("M", llvm::json::Object{
                       {"name", "process_name"},
-                      {"args", json::Object{{"name", "clangd"}}},
+                      {"args", llvm::json::Object{{"name", "clangd"}}},
                   });
   }
 
@@ -49,7 +48,7 @@ public:
 
   // We stash a Span object in the context. It will record the start/end,
   // and this also allows us to look up the parent Span's information.
-  Context beginSpan(StringRef Name, json::Object *Args) override {
+  Context beginSpan(llvm::StringRef Name, llvm::json::Object *Args) override {
     return Context::current().derive(
         SpanKey, llvm::make_unique<JSONSpan>(this, Name, Args));
   }
@@ -62,15 +61,16 @@ public:
     Context::current().getExisting(SpanKey)->markEnded();
   }
 
-  void instant(StringRef Name, json::Object &&Args) override {
+  void instant(llvm::StringRef Name, llvm::json::Object &&Args) override {
     captureThreadMetadata();
-    jsonEvent("i", json::Object{{"name", Name}, {"args", std::move(Args)}});
+    jsonEvent("i",
+              llvm::json::Object{{"name", Name}, {"args", std::move(Args)}});
   }
 
   // Record an event on the current thread. ph, pid, tid, ts are set.
   // Contents must be a list of the other JSON key/values.
-  void jsonEvent(StringRef Phase, json::Object &&Contents,
-                 uint64_t TID = get_threadid(), double Timestamp = 0) {
+  void jsonEvent(llvm::StringRef Phase, llvm::json::Object &&Contents,
+                 uint64_t TID = llvm::get_threadid(), double Timestamp = 0) {
     Contents["ts"] = Timestamp ? Timestamp : timestamp();
     Contents["tid"] = int64_t(TID);
     std::lock_guard<std::mutex> Lock(Mu);
@@ -80,9 +80,9 @@ public:
 private:
   class JSONSpan {
   public:
-    JSONSpan(JSONTracer *Tracer, StringRef Name, json::Object *Args)
+    JSONSpan(JSONTracer *Tracer, llvm::StringRef Name, llvm::json::Object *Args)
         : StartTime(Tracer->timestamp()), EndTime(0), Name(Name),
-          TID(get_threadid()), Tracer(Tracer), Args(Args) {
+          TID(llvm::get_threadid()), Tracer(Tracer), Args(Args) {
       // ~JSONSpan() may run in a different thread, so we need to capture now.
       Tracer->captureThreadMetadata();
 
@@ -100,26 +100,28 @@ private:
           OriginTime = (*Parent)->StartTime;
 
         auto FlowID = nextID();
-        Tracer->jsonEvent("s",
-                          json::Object{{"id", FlowID},
-                                       {"name", "Context crosses threads"},
-                                       {"cat", "dummy"}},
-                          (*Parent)->TID, (*Parent)->StartTime);
-        Tracer->jsonEvent("f",
-                          json::Object{{"id", FlowID},
-                                       {"bp", "e"},
-                                       {"name", "Context crosses threads"},
-                                       {"cat", "dummy"}},
-                          TID);
+        Tracer->jsonEvent(
+            "s",
+            llvm::json::Object{{"id", FlowID},
+                               {"name", "Context crosses threads"},
+                               {"cat", "dummy"}},
+            (*Parent)->TID, (*Parent)->StartTime);
+        Tracer->jsonEvent(
+            "f",
+            llvm::json::Object{{"id", FlowID},
+                               {"bp", "e"},
+                               {"name", "Context crosses threads"},
+                               {"cat", "dummy"}},
+            TID);
       }
     }
 
     ~JSONSpan() {
       // Finally, record the event (ending at EndTime, not timestamp())!
       Tracer->jsonEvent("X",
-                        json::Object{{"name", std::move(Name)},
-                                     {"args", std::move(*Args)},
-                                     {"dur", EndTime - StartTime}},
+                        llvm::json::Object{{"name", std::move(Name)},
+                                           {"args", std::move(*Args)},
+                                           {"dur", EndTime - StartTime}},
                         TID, StartTime);
     }
 
@@ -137,32 +139,34 @@ private:
     std::string Name;
     uint64_t TID;
     JSONTracer *Tracer;
-    json::Object *Args;
+    llvm::json::Object *Args;
   };
   static Key<std::unique_ptr<JSONSpan>> SpanKey;
 
   // Record an event. ph and pid are set.
   // Contents must be a list of the other JSON key/values.
-  void rawEvent(StringRef Phase, json::Object &&Event) /*REQUIRES(Mu)*/ {
+  void rawEvent(llvm::StringRef Phase,
+                llvm::json::Object &&Event) /*REQUIRES(Mu)*/ {
     // PID 0 represents the clangd process.
     Event["pid"] = 0;
     Event["ph"] = Phase;
-    Out << Sep << formatv(JSONFormat, json::Value(std::move(Event)));
+    Out << Sep
+        << llvm::formatv(JSONFormat, llvm::json::Value(std::move(Event)));
     Sep = ",\n";
   }
 
   // If we haven't already, emit metadata describing this thread.
   void captureThreadMetadata() {
-    uint64_t TID = get_threadid();
+    uint64_t TID = llvm::get_threadid();
     std::lock_guard<std::mutex> Lock(Mu);
     if (ThreadsWithMD.insert(TID).second) {
-      SmallString<32> Name;
-      get_thread_name(Name);
+      llvm::SmallString<32> Name;
+      llvm::get_thread_name(Name);
       if (!Name.empty()) {
-        rawEvent("M", json::Object{
+        rawEvent("M", llvm::json::Object{
                           {"tid", int64_t(TID)},
                           {"name", "thread_name"},
-                          {"args", json::Object{{"name", Name}}},
+                          {"args", llvm::json::Object{{"name", Name}}},
                       });
       }
     }
@@ -174,10 +178,10 @@ private:
   }
 
   std::mutex Mu;
-  raw_ostream &Out /*GUARDED_BY(Mu)*/;
+  llvm::raw_ostream &Out /*GUARDED_BY(Mu)*/;
   const char *Sep /*GUARDED_BY(Mu)*/;
-  DenseSet<uint64_t> ThreadsWithMD /*GUARDED_BY(Mu)*/;
-  const sys::TimePoint<> Start;
+  llvm::DenseSet<uint64_t> ThreadsWithMD /*GUARDED_BY(Mu)*/;
+  const llvm::sys::TimePoint<> Start;
   const char *JSONFormat;
 };
 
@@ -193,31 +197,32 @@ Session::Session(EventTracer &Tracer) {
 
 Session::~Session() { T = nullptr; }
 
-std::unique_ptr<EventTracer> createJSONTracer(raw_ostream &OS, bool Pretty) {
+std::unique_ptr<EventTracer> createJSONTracer(llvm::raw_ostream &OS,
+                                              bool Pretty) {
   return llvm::make_unique<JSONTracer>(OS, Pretty);
 }
 
-void log(const Twine &Message) {
+void log(const llvm::Twine &Message) {
   if (!T)
     return;
-  T->instant("Log", json::Object{{"Message", Message.str()}});
+  T->instant("Log", llvm::json::Object{{"Message", Message.str()}});
 }
 
 // Returned context owns Args.
-static Context makeSpanContext(Twine Name, json::Object *Args) {
+static Context makeSpanContext(llvm::Twine Name, llvm::json::Object *Args) {
   if (!T)
     return Context::current().clone();
-  WithContextValue WithArgs{std::unique_ptr<json::Object>(Args)};
+  WithContextValue WithArgs{std::unique_ptr<llvm::json::Object>(Args)};
   return T->beginSpan(Name.isSingleStringRef() ? Name.getSingleStringRef()
-                                               : StringRef(Name.str()),
+                                               : llvm::StringRef(Name.str()),
                       Args);
 }
 
 // Span keeps a non-owning pointer to the args, which is how users access them.
 // The args are owned by the context though. They stick around until the
 // beginSpan() context is destroyed, when the tracing engine will consume them.
-Span::Span(Twine Name)
-    : Args(T ? new json::Object() : nullptr),
+Span::Span(llvm::Twine Name)
+    : Args(T ? new llvm::json::Object() : nullptr),
       RestoreCtx(makeSpanContext(Name, Args)) {}
 
 Span::~Span() {

Modified: clang-tools-extra/trunk/clangd/URI.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/URI.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/URI.cpp (original)
+++ clang-tools-extra/trunk/clangd/URI.cpp Mon Jan  7 07:45:19 2019
@@ -20,13 +20,13 @@
 
 LLVM_INSTANTIATE_REGISTRY(clang::clangd::URISchemeRegistry)
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
 
-inline Error make_string_error(const Twine &Message) {
-  return make_error<StringError>(Message, inconvertibleErrorCode());
+inline llvm::Error make_string_error(const llvm::Twine &Message) {
+  return llvm::make_error<llvm::StringError>(Message,
+                                             llvm::inconvertibleErrorCode());
 }
 
 /// \brief This manages file paths in the file system. All paths in the scheme
@@ -35,8 +35,9 @@ inline Error make_string_error(const Twi
 /// registry.
 class FileSystemScheme : public URIScheme {
 public:
-  Expected<std::string> getAbsolutePath(StringRef /*Authority*/, StringRef Body,
-                                        StringRef /*HintPath*/) const override {
+  llvm::Expected<std::string>
+  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
+                  llvm::StringRef /*HintPath*/) const override {
     if (!Body.startswith("/"))
       return make_string_error("File scheme: expect body to be an absolute "
                                "path starting with '/': " +
@@ -44,26 +45,26 @@ public:
     // For Windows paths e.g. /X:
     if (Body.size() > 2 && Body[0] == '/' && Body[2] == ':')
       Body.consume_front("/");
-    SmallVector<char, 16> Path(Body.begin(), Body.end());
-    sys::path::native(Path);
+    llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
+    llvm::sys::path::native(Path);
     return std::string(Path.begin(), Path.end());
   }
 
-  Expected<URI> uriFromAbsolutePath(StringRef AbsolutePath) const override {
-    using namespace llvm::sys;
-
+  llvm::Expected<URI>
+  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
     std::string Body;
     // For Windows paths e.g. X:
     if (AbsolutePath.size() > 1 && AbsolutePath[1] == ':')
       Body = "/";
-    Body += path::convert_to_slash(AbsolutePath);
+    Body += llvm::sys::path::convert_to_slash(AbsolutePath);
     return URI("file", /*Authority=*/"", Body);
   }
 };
 
-Expected<std::unique_ptr<URIScheme>> findSchemeByName(StringRef Scheme) {
+llvm::Expected<std::unique_ptr<URIScheme>>
+findSchemeByName(llvm::StringRef Scheme) {
   if (Scheme == "file")
-    return make_unique<FileSystemScheme>();
+    return llvm::make_unique<FileSystemScheme>();
 
   for (auto I = URISchemeRegistry::begin(), E = URISchemeRegistry::end();
        I != E; ++I) {
@@ -96,12 +97,12 @@ bool shouldEscape(unsigned char C) {
 /// - Unreserved characters are not escaped.
 /// - Reserved characters always escaped with exceptions like '/'.
 /// - All other characters are escaped.
-std::string percentEncode(StringRef Content) {
+std::string percentEncode(llvm::StringRef Content) {
   std::string Result;
-  raw_string_ostream OS(Result);
+  llvm::raw_string_ostream OS(Result);
   for (unsigned char C : Content)
     if (shouldEscape(C))
-      OS << '%' << format_hex_no_prefix(C, 2, /*Upper = */ true);
+      OS << '%' << llvm::format_hex_no_prefix(C, 2, /*Upper = */ true);
     else
       OS << C;
 
@@ -110,16 +111,16 @@ std::string percentEncode(StringRef Cont
 }
 
 /// Decodes a string according to percent-encoding.
-std::string percentDecode(StringRef Content) {
+std::string percentDecode(llvm::StringRef Content) {
   std::string Result;
   for (auto I = Content.begin(), E = Content.end(); I != E; ++I) {
     if (*I != '%') {
       Result += *I;
       continue;
     }
-    if (*I == '%' && I + 2 < Content.end() && isHexDigit(*(I + 1)) &&
-        isHexDigit(*(I + 2))) {
-      Result.push_back(hexFromNibbles(*(I + 1), *(I + 2)));
+    if (*I == '%' && I + 2 < Content.end() && llvm::isHexDigit(*(I + 1)) &&
+        llvm::isHexDigit(*(I + 2))) {
+      Result.push_back(llvm::hexFromNibbles(*(I + 1), *(I + 2)));
       I += 2;
     } else
       Result.push_back(*I);
@@ -127,19 +128,20 @@ std::string percentDecode(StringRef Cont
   return Result;
 }
 
-bool isValidScheme(StringRef Scheme) {
+bool isValidScheme(llvm::StringRef Scheme) {
   if (Scheme.empty())
     return false;
-  if (!isAlpha(Scheme[0]))
+  if (!llvm::isAlpha(Scheme[0]))
     return false;
   return std::all_of(Scheme.begin() + 1, Scheme.end(), [](char C) {
-    return isAlnum(C) || C == '+' || C == '.' || C == '-';
+    return llvm::isAlnum(C) || C == '+' || C == '.' || C == '-';
   });
 }
 
 } // namespace
 
-URI::URI(StringRef Scheme, StringRef Authority, StringRef Body)
+URI::URI(llvm::StringRef Scheme, llvm::StringRef Authority,
+         llvm::StringRef Body)
     : Scheme(Scheme), Authority(Authority), Body(Body) {
   assert(!Scheme.empty());
   assert((Authority.empty() || Body.startswith("/")) &&
@@ -148,31 +150,31 @@ URI::URI(StringRef Scheme, StringRef Aut
 
 std::string URI::toString() const {
   std::string Result;
-  raw_string_ostream OS(Result);
+  llvm::raw_string_ostream OS(Result);
   OS << percentEncode(Scheme) << ":";
   if (Authority.empty() && Body.empty())
     return OS.str();
   // If authority if empty, we only print body if it starts with "/"; otherwise,
   // the URI is invalid.
-  if (!Authority.empty() || StringRef(Body).startswith("/"))
+  if (!Authority.empty() || llvm::StringRef(Body).startswith("/"))
     OS << "//" << percentEncode(Authority);
   OS << percentEncode(Body);
   OS.flush();
   return Result;
 }
 
-Expected<URI> URI::parse(StringRef OrigUri) {
+llvm::Expected<URI> URI::parse(llvm::StringRef OrigUri) {
   URI U;
-  StringRef Uri = OrigUri;
+  llvm::StringRef Uri = OrigUri;
 
   auto Pos = Uri.find(':');
-  if (Pos == StringRef::npos)
+  if (Pos == llvm::StringRef::npos)
     return make_string_error("Scheme must be provided in URI: " + OrigUri);
   auto SchemeStr = Uri.substr(0, Pos);
   U.Scheme = percentDecode(SchemeStr);
   if (!isValidScheme(U.Scheme))
-    return make_string_error(
-        formatv("Invalid scheme: {0} (decoded: {1})", SchemeStr, U.Scheme));
+    return make_string_error(llvm::formatv("Invalid scheme: {0} (decoded: {1})",
+                                           SchemeStr, U.Scheme));
   Uri = Uri.substr(Pos + 1);
   if (Uri.consume_front("//")) {
     Pos = Uri.find('/');
@@ -183,8 +185,9 @@ Expected<URI> URI::parse(StringRef OrigU
   return U;
 }
 
-Expected<URI> URI::create(StringRef AbsolutePath, StringRef Scheme) {
-  if (!sys::path::is_absolute(AbsolutePath))
+llvm::Expected<URI> URI::create(llvm::StringRef AbsolutePath,
+                                llvm::StringRef Scheme) {
+  if (!llvm::sys::path::is_absolute(AbsolutePath))
     return make_string_error("Not a valid absolute path: " + AbsolutePath);
   auto S = findSchemeByName(Scheme);
   if (!S)
@@ -192,8 +195,8 @@ Expected<URI> URI::create(StringRef Abso
   return S->get()->uriFromAbsolutePath(AbsolutePath);
 }
 
-URI URI::create(StringRef AbsolutePath) {
-  if (!sys::path::is_absolute(AbsolutePath))
+URI URI::create(llvm::StringRef AbsolutePath) {
+  if (!llvm::sys::path::is_absolute(AbsolutePath))
     llvm_unreachable(
         ("Not a valid absolute path: " + AbsolutePath).str().c_str());
   for (auto &Entry : URISchemeRegistry::entries()) {
@@ -202,7 +205,7 @@ URI URI::create(StringRef AbsolutePath)
     // should be just skipped.
     if (!URI) {
       // Ignore the error.
-      consumeError(URI.takeError());
+      llvm::consumeError(URI.takeError());
       continue;
     }
     return std::move(*URI);
@@ -211,22 +214,24 @@ URI URI::create(StringRef AbsolutePath)
   return URI::createFile(AbsolutePath);
 }
 
-URI URI::createFile(StringRef AbsolutePath) {
+URI URI::createFile(llvm::StringRef AbsolutePath) {
   auto U = FileSystemScheme().uriFromAbsolutePath(AbsolutePath);
   if (!U)
     llvm_unreachable(llvm::toString(U.takeError()).c_str());
   return std::move(*U);
 }
 
-Expected<std::string> URI::resolve(const URI &Uri, StringRef HintPath) {
+llvm::Expected<std::string> URI::resolve(const URI &Uri,
+                                         llvm::StringRef HintPath) {
   auto S = findSchemeByName(Uri.Scheme);
   if (!S)
     return S.takeError();
   return S->get()->getAbsolutePath(Uri.Authority, Uri.Body, HintPath);
 }
 
-Expected<std::string> URI::resolvePath(StringRef AbsPath, StringRef HintPath) {
-  if (!sys::path::is_absolute(AbsPath))
+llvm::Expected<std::string> URI::resolvePath(llvm::StringRef AbsPath,
+                                             llvm::StringRef HintPath) {
+  if (!llvm::sys::path::is_absolute(AbsPath))
     llvm_unreachable(("Not a valid absolute path: " + AbsPath).str().c_str());
   for (auto &Entry : URISchemeRegistry::entries()) {
     auto S = Entry.instantiate();
@@ -235,7 +240,7 @@ Expected<std::string> URI::resolvePath(S
     // should be just skipped.
     if (!U) {
       // Ignore the error.
-      consumeError(U.takeError());
+      llvm::consumeError(U.takeError());
       continue;
     }
     return S->getAbsolutePath(U->Authority, U->Body, HintPath);
@@ -244,7 +249,7 @@ Expected<std::string> URI::resolvePath(S
   return AbsPath;
 }
 
-Expected<std::string> URI::includeSpelling(const URI &Uri) {
+llvm::Expected<std::string> URI::includeSpelling(const URI &Uri) {
   auto S = findSchemeByName(Uri.Scheme);
   if (!S)
     return S.takeError();

Modified: clang-tools-extra/trunk/clangd/XRefs.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/XRefs.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/XRefs.cpp (original)
+++ clang-tools-extra/trunk/clangd/XRefs.cpp Mon Jan  7 07:45:19 2019
@@ -18,7 +18,6 @@
 #include "clang/Index/USRGeneration.h"
 #include "llvm/Support/Path.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -46,7 +45,8 @@ void logIfOverflow(const SymbolLocation
 // TUPath is used to resolve the path of URI.
 // FIXME: figure out a good home for it, and share the implementation with
 // FindSymbols.
-Optional<Location> toLSPLocation(const SymbolLocation &Loc, StringRef TUPath) {
+llvm::Optional<Location> toLSPLocation(const SymbolLocation &Loc,
+                                       llvm::StringRef TUPath) {
   if (!Loc)
     return None;
   auto Uri = URI::parse(Loc.FileURI);
@@ -71,7 +71,7 @@ Optional<Location> toLSPLocation(const S
 }
 
 struct MacroDecl {
-  StringRef Name;
+  llvm::StringRef Name;
   const MacroInfo *Info;
 };
 
@@ -88,7 +88,7 @@ class DeclarationAndMacrosFinder : publi
   // explicitly in the code.
   // True means the declaration is explicitly referenced at least once; false
   // otherwise.
-  DenseMap<const Decl *, bool> Decls;
+  llvm::DenseMap<const Decl *, bool> Decls;
   const SourceLocation &SearchedLocation;
   const ASTContext &AST;
   Preprocessor &PP;
@@ -134,7 +134,7 @@ public:
 
   bool
   handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
-                      ArrayRef<index::SymbolRelation> Relations,
+                      llvm::ArrayRef<index::SymbolRelation> Relations,
                       SourceLocation Loc,
                       index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
     if (Loc == SearchedLocation) {
@@ -222,8 +222,8 @@ Range getTokenRange(ParsedAST &AST, Sour
           sourceLocToPosition(SourceMgr, LocEnd)};
 }
 
-Optional<Location> makeLocation(ParsedAST &AST, SourceLocation TokLoc,
-                                StringRef TUPath) {
+llvm::Optional<Location> makeLocation(ParsedAST &AST, SourceLocation TokLoc,
+                                      llvm::StringRef TUPath) {
   const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
   const FileEntry *F = SourceMgr.getFileEntryForID(SourceMgr.getFileID(TokLoc));
   if (!F)
@@ -294,12 +294,12 @@ std::vector<Location> findDefinitions(Pa
   //   4. Return all populated locations for all symbols, definition first (
   //      which  we think is the users wants most often).
   struct CandidateLocation {
-    Optional<Location> Def;
-    Optional<Location> Decl;
+    llvm::Optional<Location> Def;
+    llvm::Optional<Location> Decl;
   };
   // We respect the order in Symbols.Decls.
-  SmallVector<CandidateLocation, 8> ResultCandidates;
-  DenseMap<SymbolID, size_t> CandidatesIndex;
+  llvm::SmallVector<CandidateLocation, 8> ResultCandidates;
+  llvm::DenseMap<SymbolID, size_t> CandidatesIndex;
 
   // Emit all symbol locations (declaration or definition) from AST.
   for (const DeclInfo &DI : Symbols.Decls) {
@@ -400,7 +400,7 @@ public:
 
   bool
   handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles,
-                      ArrayRef<index::SymbolRelation> Relations,
+                      llvm::ArrayRef<index::SymbolRelation> Relations,
                       SourceLocation Loc,
                       index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
     assert(D->isCanonicalDecl() && "expect D to be a canonical declaration");
@@ -412,7 +412,7 @@ public:
   }
 
 private:
-  SmallSet<const Decl *, 4> CanonicalTargets;
+  llvm::SmallSet<const Decl *, 4> CanonicalTargets;
   std::vector<Reference> References;
   const ASTContext &AST;
 };
@@ -478,7 +478,7 @@ static std::string typeDeclToString(cons
       printingPolicyForDecls(TD->getASTContext().getPrintingPolicy());
 
   std::string Name;
-  raw_string_ostream Stream(Name);
+  llvm::raw_string_ostream Stream(Name);
   Type.print(Stream, Policy);
 
   return Stream.str();
@@ -487,12 +487,12 @@ static std::string typeDeclToString(cons
 /// Return a string representation (e.g. "namespace ns1::ns2") of
 /// the named declaration \p ND.
 static std::string namedDeclQualifiedName(const NamedDecl *ND,
-                                          StringRef Prefix) {
+                                          llvm::StringRef Prefix) {
   PrintingPolicy Policy =
       printingPolicyForDecls(ND->getASTContext().getPrintingPolicy());
 
   std::string Name;
-  raw_string_ostream Stream(Name);
+  llvm::raw_string_ostream Stream(Name);
   Stream << Prefix << ' ';
   ND->printQualifiedName(Stream, Policy);
 
@@ -502,7 +502,7 @@ static std::string 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 Optional<std::string> getScopeName(const Decl *D) {
+static llvm::Optional<std::string> getScopeName(const Decl *D) {
   const DeclContext *DC = D->getDeclContext();
 
   if (isa<TranslationUnitDecl>(DC))
@@ -520,7 +520,7 @@ static Optional<std::string> getScopeNam
 /// Generate a \p Hover object given the declaration \p D.
 static Hover getHoverContents(const Decl *D) {
   Hover H;
-  Optional<std::string> NamedScope = getScopeName(D);
+  llvm::Optional<std::string> NamedScope = getScopeName(D);
 
   // Generate the "Declared in" section.
   if (NamedScope) {
@@ -536,7 +536,7 @@ static Hover getHoverContents(const Decl
     D = TD;
 
   std::string DeclText;
-  raw_string_ostream OS(DeclText);
+  llvm::raw_string_ostream OS(DeclText);
 
   PrintingPolicy Policy =
       printingPolicyForDecls(D->getASTContext().getPrintingPolicy());
@@ -553,7 +553,7 @@ static Hover getHoverContents(const Decl
 static Hover getHoverContents(QualType T, ASTContext &ASTCtx) {
   Hover H;
   std::string TypeText;
-  raw_string_ostream OS(TypeText);
+  llvm::raw_string_ostream OS(TypeText);
   PrintingPolicy Policy = printingPolicyForDecls(ASTCtx.getPrintingPolicy());
   T.print(OS, Policy);
   OS.flush();
@@ -562,7 +562,7 @@ static Hover getHoverContents(QualType T
 }
 
 /// Generate a \p Hover object given the macro \p MacroInf.
-static Hover getHoverContents(StringRef MacroName) {
+static Hover getHoverContents(llvm::StringRef MacroName) {
   Hover H;
 
   H.contents.value = "#define ";
@@ -582,13 +582,13 @@ namespace {
 /// a deduced type set. The AST should be improved to simplify this scenario.
 class DeducedTypeVisitor : public RecursiveASTVisitor<DeducedTypeVisitor> {
   SourceLocation SearchedLocation;
-  Optional<QualType> DeducedType;
+  llvm::Optional<QualType> DeducedType;
 
 public:
   DeducedTypeVisitor(SourceLocation SearchedLocation)
       : SearchedLocation(SearchedLocation) {}
 
-  Optional<QualType> getDeducedType() { return DeducedType; }
+  llvm::Optional<QualType> getDeducedType() { return DeducedType; }
 
   // Handle auto initializers:
   //- auto i = 1;
@@ -663,8 +663,8 @@ public:
 } // namespace
 
 /// Retrieves the deduced type at a given location (auto, decltype).
-Optional<QualType> getDeducedType(ParsedAST &AST,
-                                  SourceLocation SourceLocationBeg) {
+llvm::Optional<QualType> getDeducedType(ParsedAST &AST,
+                                        SourceLocation SourceLocationBeg) {
   Token Tok;
   auto &ASTCtx = AST.getASTContext();
   // Only try to find a deduced type if the token is auto or decltype.
@@ -683,7 +683,7 @@ Optional<QualType> getDeducedType(Parsed
   return V.getDeducedType();
 }
 
-Optional<Hover> getHover(ParsedAST &AST, Position Pos) {
+llvm::Optional<Hover> getHover(ParsedAST &AST, Position Pos) {
   const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
   SourceLocation SourceLocationBeg =
       getBeginningOfIdentifier(AST, Pos, SourceMgr.getMainFileID());

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp (original)
+++ clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp Mon Jan  7 07:45:19 2019
@@ -21,7 +21,6 @@
 const char *IndexFilename;
 const char *RequestsFilename;
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -41,16 +40,17 @@ std::vector<FuzzyFindRequest> extractQue
                   std::istreambuf_iterator<char>());
 
   std::vector<FuzzyFindRequest> Requests;
-  auto JSONArray = json::parse(Log);
+  auto JSONArray = llvm::json::parse(Log);
 
   // Panic if the provided file couldn't be parsed.
   if (!JSONArray) {
-    errs() << "Error when parsing JSON requests file: "
-           << toString(JSONArray.takeError());
+    llvm::errs() << "Error when parsing JSON requests file: "
+                 << llvm::toString(JSONArray.takeError());
     exit(1);
   }
   if (!JSONArray->getAsArray()) {
-    errs() << "Error: top-level value is not a JSON array: " << Log << '\n';
+    llvm::errs() << "Error: top-level value is not a JSON array: " << Log
+                 << '\n';
     exit(1);
   }
 
@@ -58,7 +58,7 @@ std::vector<FuzzyFindRequest> extractQue
     FuzzyFindRequest Request;
     // Panic if the provided file couldn't be parsed.
     if (!fromJSON(Item, Request)) {
-      errs() << "Error when deserializing request: " << Item << '\n';
+      llvm::errs() << "Error when deserializing request: " << Item << '\n';
       exit(1);
     }
     Requests.push_back(Request);
@@ -94,9 +94,9 @@ BENCHMARK(DexQueries);
 // FIXME(kbobyrev): Create a logger wrapper to suppress debugging info printer.
 int main(int argc, char *argv[]) {
   if (argc < 3) {
-    errs() << "Usage: " << argv[0]
-           << " global-symbol-index.yaml requests.json "
-              "BENCHMARK_OPTIONS...\n";
+    llvm::errs() << "Usage: " << argv[0]
+                 << " global-symbol-index.yaml requests.json "
+                    "BENCHMARK_OPTIONS...\n";
     return -1;
   }
   IndexFilename = argv[1];

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/Background.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Background.cpp Mon Jan  7 07:45:19 2019
@@ -35,7 +35,6 @@
 #include <string>
 #include <thread>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -119,11 +118,11 @@ createFileFilter(const llvm::StringMap<F
 } // namespace
 
 BackgroundIndex::BackgroundIndex(
-    Context BackgroundContext, StringRef ResourceDir,
+    Context BackgroundContext, llvm::StringRef ResourceDir,
     const FileSystemProvider &FSProvider, const GlobalCompilationDatabase &CDB,
     BackgroundIndexStorage::Factory IndexStorageFactory,
     size_t BuildIndexPeriodMs, size_t ThreadPoolSize)
-    : SwapIndex(make_unique<MemIndex>()), ResourceDir(ResourceDir),
+    : SwapIndex(llvm::make_unique<MemIndex>()), ResourceDir(ResourceDir),
       FSProvider(FSProvider), CDB(CDB),
       BackgroundContext(std::move(BackgroundContext)),
       BuildIndexPeriodMs(BuildIndexPeriodMs),
@@ -163,7 +162,7 @@ void BackgroundIndex::stop() {
 void BackgroundIndex::run() {
   WithContext Background(BackgroundContext.clone());
   while (true) {
-    Optional<Task> Task;
+    llvm::Optional<Task> Task;
     ThreadPriority Priority;
     {
       std::unique_lock<std::mutex> Lock(QueueMu);
@@ -260,15 +259,15 @@ void BackgroundIndex::enqueueTask(Task T
 }
 
 /// Given index results from a TU, only update files in \p FilesToUpdate.
-void BackgroundIndex::update(StringRef MainFile, IndexFileIn Index,
-                             const StringMap<FileDigest> &FilesToUpdate,
+void BackgroundIndex::update(llvm::StringRef MainFile, IndexFileIn Index,
+                             const llvm::StringMap<FileDigest> &FilesToUpdate,
                              BackgroundIndexStorage *IndexStorage) {
   // Partition symbols/references into files.
   struct File {
-    DenseSet<const Symbol *> Symbols;
-    DenseSet<const Ref *> Refs;
+    llvm::DenseSet<const Symbol *> Symbols;
+    llvm::DenseSet<const Ref *> Refs;
   };
-  StringMap<File> Files;
+  llvm::StringMap<File> Files;
   URIToFileCache URICache(MainFile);
   for (const auto &Sym : *Index.Symbols) {
     if (Sym.CanonicalDeclaration) {
@@ -287,7 +286,7 @@ void BackgroundIndex::update(StringRef M
         Files[DefPath].Symbols.insert(&Sym);
     }
   }
-  DenseMap<const Ref *, SymbolID> RefToIDs;
+  llvm::DenseMap<const Ref *, SymbolID> RefToIDs;
   for (const auto &SymRefs : *Index.Refs) {
     for (const auto &R : SymRefs.second) {
       auto Path = URICache.resolve(R.Location.FileURI);
@@ -301,7 +300,7 @@ void BackgroundIndex::update(StringRef M
 
   // Build and store new slabs for each updated file.
   for (const auto &F : Files) {
-    StringRef Path = F.first();
+    llvm::StringRef Path = F.first();
     vlog("Update symbols in {0}", Path);
     SymbolSlab::Builder Syms;
     RefSlab::Builder Refs;
@@ -362,22 +361,22 @@ void BackgroundIndex::buildIndex() {
   }
 }
 
-Error BackgroundIndex::index(tooling::CompileCommand Cmd,
-                             BackgroundIndexStorage *IndexStorage) {
+llvm::Error BackgroundIndex::index(tooling::CompileCommand Cmd,
+                                   BackgroundIndexStorage *IndexStorage) {
   trace::Span Tracer("BackgroundIndex");
   SPAN_ATTACH(Tracer, "file", Cmd.Filename);
-  SmallString<128> AbsolutePath;
-  if (sys::path::is_absolute(Cmd.Filename)) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
     AbsolutePath = Cmd.Filename;
   } else {
     AbsolutePath = Cmd.Directory;
-    sys::path::append(AbsolutePath, Cmd.Filename);
+    llvm::sys::path::append(AbsolutePath, Cmd.Filename);
   }
 
   auto FS = FSProvider.getFileSystem();
   auto Buf = FS->getBufferForFile(AbsolutePath);
   if (!Buf)
-    return errorCodeToError(Buf.getError());
+    return llvm::errorCodeToError(Buf.getError());
   auto Hash = digest(Buf->get()->getBuffer());
 
   // Take a snapshot of the digests to avoid locking for each file in the TU.
@@ -386,31 +385,31 @@ Error BackgroundIndex::index(tooling::Co
     std::lock_guard<std::mutex> Lock(DigestsMu);
     if (IndexedFileDigests.lookup(AbsolutePath) == Hash) {
       vlog("No need to index {0}, already up to date", AbsolutePath);
-      return Error::success();
+      return llvm::Error::success();
     }
 
     DigestsSnapshot = IndexedFileDigests;
   }
 
-  log("Indexing {0} (digest:={1})", Cmd.Filename, toHex(Hash));
+  log("Indexing {0} (digest:={1})", Cmd.Filename, llvm::toHex(Hash));
   ParseInputs Inputs;
   Inputs.FS = std::move(FS);
   Inputs.FS->setCurrentWorkingDirectory(Cmd.Directory);
   Inputs.CompileCommand = std::move(Cmd);
   auto CI = buildCompilerInvocation(Inputs);
   if (!CI)
-    return createStringError(inconvertibleErrorCode(),
-                             "Couldn't build compiler invocation");
+    return llvm::createStringError(llvm::inconvertibleErrorCode(),
+                                   "Couldn't build compiler invocation");
   IgnoreDiagnostics IgnoreDiags;
   auto Clang = prepareCompilerInstance(
       std::move(CI), /*Preamble=*/nullptr, std::move(*Buf),
       std::make_shared<PCHContainerOperations>(), Inputs.FS, IgnoreDiags);
   if (!Clang)
-    return createStringError(inconvertibleErrorCode(),
-                             "Couldn't build compiler instance");
+    return llvm::createStringError(llvm::inconvertibleErrorCode(),
+                                   "Couldn't build compiler instance");
 
   SymbolCollector::Options IndexOpts;
-  StringMap<FileDigest> FilesToUpdate;
+  llvm::StringMap<FileDigest> FilesToUpdate;
   IndexOpts.FileFilter = createFileFilter(DigestsSnapshot, FilesToUpdate);
   IndexFileIn Index;
   auto Action = createStaticIndexingAction(
@@ -425,15 +424,17 @@ Error BackgroundIndex::index(tooling::Co
 
   const FrontendInputFile &Input = Clang->getFrontendOpts().Inputs.front();
   if (!Action->BeginSourceFile(*Clang, Input))
-    return createStringError(inconvertibleErrorCode(),
-                             "BeginSourceFile() failed");
+    return llvm::createStringError(llvm::inconvertibleErrorCode(),
+                                   "BeginSourceFile() failed");
   if (!Action->Execute())
-    return createStringError(inconvertibleErrorCode(), "Execute() failed");
+    return llvm::createStringError(llvm::inconvertibleErrorCode(),
+                                   "Execute() failed");
   Action->EndSourceFile();
   if (Clang->hasDiagnostics() &&
       Clang->getDiagnostics().hasUncompilableErrorOccurred()) {
-    return createStringError(inconvertibleErrorCode(),
-                             "IndexingAction failed: has uncompilable errors");
+    return llvm::createStringError(
+        llvm::inconvertibleErrorCode(),
+        "IndexingAction failed: has uncompilable errors");
   }
 
   assert(Index.Symbols && Index.Refs && Index.Sources
@@ -460,7 +461,7 @@ Error BackgroundIndex::index(tooling::Co
     reset(
         IndexedSymbols.buildIndex(IndexType::Light, DuplicateHandling::Merge));
 
-  return Error::success();
+  return llvm::Error::success();
 }
 
 } // namespace clangd

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp Mon Jan  7 07:45:19 2019
@@ -13,49 +13,50 @@
 #include "llvm/Support/Path.h"
 #include <algorithm>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
 const char IWYUPragma[] = "// IWYU pragma: private, include ";
 } // namespace
 
-void CanonicalIncludes::addPathSuffixMapping(StringRef Suffix,
-                                             StringRef CanonicalPath) {
-  int Components =
-      std::distance(sys::path::begin(Suffix), sys::path::end(Suffix));
+void CanonicalIncludes::addPathSuffixMapping(llvm::StringRef Suffix,
+                                             llvm::StringRef CanonicalPath) {
+  int Components = std::distance(llvm::sys::path::begin(Suffix),
+                                 llvm::sys::path::end(Suffix));
   MaxSuffixComponents = std::max(MaxSuffixComponents, Components);
   SuffixHeaderMapping[Suffix] = CanonicalPath;
 }
 
-void CanonicalIncludes::addMapping(StringRef Path, StringRef CanonicalPath) {
+void CanonicalIncludes::addMapping(llvm::StringRef Path,
+                                   llvm::StringRef CanonicalPath) {
   FullPathMapping[Path] = CanonicalPath;
 }
 
-void CanonicalIncludes::addSymbolMapping(StringRef QualifiedName,
-                                         StringRef CanonicalPath) {
+void CanonicalIncludes::addSymbolMapping(llvm::StringRef QualifiedName,
+                                         llvm::StringRef CanonicalPath) {
   this->SymbolMapping[QualifiedName] = CanonicalPath;
 }
 
-StringRef CanonicalIncludes::mapHeader(ArrayRef<std::string> Headers,
-                                       StringRef QualifiedName) const {
+llvm::StringRef
+CanonicalIncludes::mapHeader(llvm::ArrayRef<std::string> Headers,
+                             llvm::StringRef QualifiedName) const {
   assert(!Headers.empty());
   auto SE = SymbolMapping.find(QualifiedName);
   if (SE != SymbolMapping.end())
     return SE->second;
   // Find the first header such that the extension is not '.inc', and isn't a
   // recognized non-header file
-  auto I = llvm::find_if(Headers, [](StringRef Include) {
+  auto I = llvm::find_if(Headers, [](llvm::StringRef Include) {
     // Skip .inc file whose including header file should
     // be #included instead.
     return !Include.endswith(".inc");
   });
   if (I == Headers.end())
     return Headers[0]; // Fallback to the declaring header.
-  StringRef Header = *I;
+  llvm::StringRef Header = *I;
   // If Header is not expected be included (e.g. .cc file), we fall back to
   // the declaring header.
-  StringRef Ext = sys::path::extension(Header).trim('.');
+  llvm::StringRef Ext = llvm::sys::path::extension(Header).trim('.');
   // Include-able headers must have precompile type. Treat files with
   // non-recognized extenstions (TY_INVALID) as headers.
   auto ExtType = driver::types::lookupTypeForExtension(Ext);
@@ -68,7 +69,8 @@ StringRef CanonicalIncludes::mapHeader(A
     return MapIt->second;
 
   int Components = 1;
-  for (auto It = sys::path::rbegin(Header), End = sys::path::rend(Header);
+  for (auto It = llvm::sys::path::rbegin(Header),
+            End = llvm::sys::path::rend(Header);
        It != End && Components <= MaxSuffixComponents; ++It, ++Components) {
     auto SubPath = Header.substr(It->data() - Header.begin());
     auto MappingIt = SuffixHeaderMapping.find(SubPath);
@@ -85,7 +87,7 @@ collectIWYUHeaderMaps(CanonicalIncludes
     PragmaCommentHandler(CanonicalIncludes *Includes) : Includes(Includes) {}
 
     bool HandleComment(Preprocessor &PP, SourceRange Range) override {
-      StringRef Text =
+      llvm::StringRef Text =
           Lexer::getSourceText(CharSourceRange::getCharRange(Range),
                                PP.getSourceManager(), PP.getLangOpts());
       if (!Text.consume_front(IWYUPragma))

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/FileIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/FileIndex.cpp Mon Jan  7 07:45:19 2019
@@ -24,13 +24,12 @@
 #include "llvm/ADT/StringRef.h"
 #include <memory>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
 static std::pair<SymbolSlab, RefSlab>
 indexSymbols(ASTContext &AST, std::shared_ptr<Preprocessor> PP,
-             ArrayRef<Decl *> DeclsToIndex, bool IsIndexMainAST) {
+             llvm::ArrayRef<Decl *> DeclsToIndex, bool IsIndexMainAST) {
   SymbolCollector::Options CollectorOpts;
   // FIXME(ioeric): we might also want to collect include headers. We would need
   // to make sure all includes are canonicalized (with CanonicalIncludes), which
@@ -116,7 +115,7 @@ FileSymbols::buildIndex(IndexType Type,
   std::vector<Symbol> SymsStorage;
   switch (DuplicateHandle) {
   case DuplicateHandling::Merge: {
-    DenseMap<SymbolID, Symbol> Merged;
+    llvm::DenseMap<SymbolID, Symbol> Merged;
     for (const auto &Slab : SymbolSlabs) {
       for (const auto &Sym : *Slab) {
         auto I = Merged.try_emplace(Sym.ID, Sym);
@@ -143,9 +142,9 @@ FileSymbols::buildIndex(IndexType Type,
   }
 
   std::vector<Ref> RefsStorage; // Contiguous ranges for each SymbolID.
-  DenseMap<SymbolID, ArrayRef<Ref>> AllRefs;
+  llvm::DenseMap<SymbolID, llvm::ArrayRef<Ref>> AllRefs;
   {
-    DenseMap<SymbolID, SmallVector<Ref, 4>> MergedRefs;
+    llvm::DenseMap<SymbolID, llvm::SmallVector<Ref, 4>> MergedRefs;
     size_t Count = 0;
     for (const auto &RefSlab : RefSlabs)
       for (const auto &Sym : *RefSlab) {
@@ -161,8 +160,8 @@ FileSymbols::buildIndex(IndexType Type,
       llvm::copy(SymRefs, back_inserter(RefsStorage));
       AllRefs.try_emplace(
           Sym.first,
-          ArrayRef<Ref>(&RefsStorage[RefsStorage.size() - SymRefs.size()],
-                        SymRefs.size()));
+          llvm::ArrayRef<Ref>(&RefsStorage[RefsStorage.size() - SymRefs.size()],
+                              SymRefs.size()));
     }
   }
 
@@ -177,13 +176,13 @@ FileSymbols::buildIndex(IndexType Type,
   switch (Type) {
   case IndexType::Light:
     return llvm::make_unique<MemIndex>(
-        make_pointee_range(AllSymbols), std::move(AllRefs),
+        llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
         std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
                         std::move(RefsStorage), std::move(SymsStorage)),
         StorageSize);
   case IndexType::Heavy:
     return llvm::make_unique<dex::Dex>(
-        make_pointee_range(AllSymbols), std::move(AllRefs),
+        llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
         std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
                         std::move(RefsStorage), std::move(SymsStorage)),
         StorageSize);

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/Index.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Index.cpp Mon Jan  7 07:45:19 2019
@@ -14,7 +14,6 @@
 #include "llvm/Support/Error.h"
 #include "llvm/Support/raw_ostream.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -35,14 +34,14 @@ void SymbolLocation::Position::setColumn
   Column = Col;
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const SymbolLocation &L) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const SymbolLocation &L) {
   if (!L)
     return OS << "(none)";
   return OS << L.FileURI << "[" << L.Start.line() << ":" << L.Start.column()
             << "-" << L.End.line() << ":" << L.End.column() << ")";
 }
 
-raw_ostream &operator<<(raw_ostream &OS, SymbolOrigin O) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, SymbolOrigin O) {
   if (O == SymbolOrigin::Unknown)
     return OS << "unknown";
   constexpr static char Sigils[] = "ADSM4567";
@@ -52,7 +51,7 @@ raw_ostream &operator<<(raw_ostream &OS,
   return OS;
 }
 
-raw_ostream &operator<<(raw_ostream &OS, Symbol::SymbolFlag F) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, Symbol::SymbolFlag F) {
   if (F == Symbol::None)
     return OS << "None";
   std::string s;
@@ -60,10 +59,10 @@ raw_ostream &operator<<(raw_ostream &OS,
     s += "deprecated|";
   if (F & Symbol::IndexedForCodeCompletion)
     s += "completion|";
-  return OS << StringRef(s).rtrim('|');
+  return OS << llvm::StringRef(s).rtrim('|');
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const Symbol &S) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Symbol &S) {
   return OS << S.Scope << S.Name;
 }
 
@@ -85,8 +84,8 @@ SymbolSlab::const_iterator SymbolSlab::f
 }
 
 // Copy the underlying data of the symbol into the owned arena.
-static void own(Symbol &S, UniqueStringSaver &Strings) {
-  visitStrings(S, [&](StringRef &V) { V = Strings.save(V); });
+static void own(Symbol &S, llvm::UniqueStringSaver &Strings) {
+  visitStrings(S, [&](llvm::StringRef &V) { V = Strings.save(V); });
 }
 
 void SymbolSlab::Builder::insert(const Symbol &S) {
@@ -106,14 +105,14 @@ SymbolSlab SymbolSlab::Builder::build()
   llvm::sort(Symbols,
              [](const Symbol &L, const Symbol &R) { return L.ID < R.ID; });
   // We may have unused strings from overwritten symbols. Build a new arena.
-  BumpPtrAllocator NewArena;
-  UniqueStringSaver Strings(NewArena);
+  llvm::BumpPtrAllocator NewArena;
+  llvm::UniqueStringSaver Strings(NewArena);
   for (auto &S : Symbols)
     own(S, Strings);
   return SymbolSlab(std::move(NewArena), std::move(Symbols));
 }
 
-raw_ostream &operator<<(raw_ostream &OS, RefKind K) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, RefKind K) {
   if (K == RefKind::Unknown)
     return OS << "Unknown";
   static const std::vector<const char *> Messages = {"Decl", "Def", "Ref"};
@@ -129,7 +128,7 @@ raw_ostream &operator<<(raw_ostream &OS,
   return OS;
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const Ref &R) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Ref &R) {
   return OS << R.Location << ":" << R.Kind;
 }
 
@@ -143,7 +142,7 @@ void RefSlab::Builder::insert(const Symb
 RefSlab RefSlab::Builder::build() && {
   // We can reuse the arena, as it only has unique strings and we need them all.
   // Reallocate refs on the arena to reduce waste and indirections when reading.
-  std::vector<std::pair<SymbolID, ArrayRef<Ref>>> Result;
+  std::vector<std::pair<SymbolID, llvm::ArrayRef<Ref>>> Result;
   Result.reserve(Refs.size());
   size_t NumRefs = 0;
   for (auto &Sym : Refs) {
@@ -155,7 +154,7 @@ RefSlab RefSlab::Builder::build() && {
     NumRefs += SymRefs.size();
     auto *Array = Arena.Allocate<Ref>(SymRefs.size());
     std::uninitialized_copy(SymRefs.begin(), SymRefs.end(), Array);
-    Result.emplace_back(Sym.first, ArrayRef<Ref>(Array, SymRefs.size()));
+    Result.emplace_back(Sym.first, llvm::ArrayRef<Ref>(Array, SymRefs.size()));
   }
   return RefSlab(std::move(Result), std::move(Arena), NumRefs);
 }
@@ -174,8 +173,8 @@ std::shared_ptr<SymbolIndex> SwapIndex::
   return Index;
 }
 
-bool fromJSON(const json::Value &Parameters, FuzzyFindRequest &Request) {
-  json::ObjectMapper O(Parameters);
+bool fromJSON(const llvm::json::Value &Parameters, FuzzyFindRequest &Request) {
+  llvm::json::ObjectMapper O(Parameters);
   int64_t Limit;
   bool OK =
       O && O.map("Query", Request.Query) && O.map("Scopes", Request.Scopes) &&
@@ -187,27 +186,27 @@ bool fromJSON(const json::Value &Paramet
   return OK;
 }
 
-json::Value toJSON(const FuzzyFindRequest &Request) {
-  return json::Object{
+llvm::json::Value toJSON(const FuzzyFindRequest &Request) {
+  return llvm::json::Object{
       {"Query", Request.Query},
-      {"Scopes", json::Array{Request.Scopes}},
+      {"Scopes", llvm::json::Array{Request.Scopes}},
       {"AnyScope", Request.AnyScope},
       {"Limit", Request.Limit},
       {"RestrictForCodeCompletion", Request.RestrictForCodeCompletion},
-      {"ProximityPaths", json::Array{Request.ProximityPaths}},
+      {"ProximityPaths", llvm::json::Array{Request.ProximityPaths}},
   };
 }
 
 bool SwapIndex::fuzzyFind(const FuzzyFindRequest &R,
-                          function_ref<void(const Symbol &)> CB) const {
+                          llvm::function_ref<void(const Symbol &)> CB) const {
   return snapshot()->fuzzyFind(R, CB);
 }
 void SwapIndex::lookup(const LookupRequest &R,
-                       function_ref<void(const Symbol &)> CB) const {
+                       llvm::function_ref<void(const Symbol &)> CB) const {
   return snapshot()->lookup(R, CB);
 }
 void SwapIndex::refs(const RefsRequest &R,
-                     function_ref<void(const Ref &)> CB) const {
+                     llvm::function_ref<void(const Ref &)> CB) const {
   return snapshot()->refs(R, CB);
 }
 size_t SwapIndex::estimateMemoryUsage() const {

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/IndexAction.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/IndexAction.cpp Mon Jan  7 07:45:19 2019
@@ -4,7 +4,6 @@
 #include "clang/Index/IndexingAction.h"
 #include "clang/Tooling/Tooling.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -63,10 +62,10 @@ public:
 
   // Add edges from including files to includes.
   void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
-                          StringRef FileName, bool IsAngled,
+                          llvm::StringRef FileName, bool IsAngled,
                           CharSourceRange FilenameRange, const FileEntry *File,
-                          StringRef SearchPath, StringRef RelativePath,
-                          const Module *Imported,
+                          llvm::StringRef SearchPath,
+                          llvm::StringRef RelativePath, const Module *Imported,
                           SrcMgr::CharacteristicKind FileType) override {
     auto IncludeURI = toURI(File);
     if (!IncludeURI)
@@ -116,8 +115,8 @@ public:
         Includes(std::move(Includes)),
         PragmaHandler(collectIWYUHeaderMaps(this->Includes.get())) {}
 
-  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
-                                                 StringRef InFile) override {
+  std::unique_ptr<ASTConsumer>
+  CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
     CI.getPreprocessor().addCommentHandler(PragmaHandler.get());
     if (IncludeGraphCallback != nullptr)
       CI.getPreprocessor().addPPCallbacks(
@@ -137,7 +136,7 @@ public:
     const auto &CI = getCompilerInstance();
     if (CI.hasDiagnostics() &&
         CI.getDiagnostics().hasUncompilableErrorOccurred()) {
-      errs() << "Skipping TU due to uncompilable errors\n";
+      llvm::errs() << "Skipping TU due to uncompilable errors\n";
       return;
     }
     SymbolsCallback(Collector->takeSymbols());

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/MemIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/MemIndex.cpp Mon Jan  7 07:45:19 2019
@@ -13,7 +13,6 @@
 #include "Quality.h"
 #include "Trace.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -25,8 +24,9 @@ std::unique_ptr<SymbolIndex> MemIndex::b
                                      BackingDataSize);
 }
 
-bool MemIndex::fuzzyFind(const FuzzyFindRequest &Req,
-                         function_ref<void(const Symbol &)> Callback) const {
+bool MemIndex::fuzzyFind(
+    const FuzzyFindRequest &Req,
+    llvm::function_ref<void(const Symbol &)> Callback) const {
   assert(!StringRef(Req.Query).contains("::") &&
          "There must be no :: in query.");
   trace::Span Tracer("MemIndex fuzzyFind");
@@ -39,7 +39,7 @@ bool MemIndex::fuzzyFind(const FuzzyFind
     const Symbol *Sym = Pair.second;
 
     // Exact match against all possible scopes.
-    if (!Req.AnyScope && !is_contained(Req.Scopes, Sym->Scope))
+    if (!Req.AnyScope && !llvm::is_contained(Req.Scopes, Sym->Scope))
       continue;
     if (Req.RestrictForCodeCompletion &&
         !(Sym->Flags & Symbol::IndexedForCodeCompletion))
@@ -57,7 +57,7 @@ bool MemIndex::fuzzyFind(const FuzzyFind
 }
 
 void MemIndex::lookup(const LookupRequest &Req,
-                      function_ref<void(const Symbol &)> Callback) const {
+                      llvm::function_ref<void(const Symbol &)> Callback) const {
   trace::Span Tracer("MemIndex lookup");
   for (const auto &ID : Req.IDs) {
     auto I = Index.find(ID);
@@ -67,7 +67,7 @@ void MemIndex::lookup(const LookupReques
 }
 
 void MemIndex::refs(const RefsRequest &Req,
-                    function_ref<void(const Ref &)> Callback) const {
+                    llvm::function_ref<void(const Ref &)> Callback) const {
   trace::Span Tracer("MemIndex refs");
   for (const auto &ReqID : Req.IDs) {
     auto SymRefs = Refs.find(ReqID);

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/Merge.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Merge.cpp Mon Jan  7 07:45:19 2019
@@ -14,7 +14,6 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/raw_ostream.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -23,8 +22,9 @@ namespace clangd {
 //          - find the generating file from each Symbol which is Static-only
 //          - ask Dynamic if it has that file (needs new SymbolIndex method)
 //          - if so, drop the Symbol.
-bool MergedIndex::fuzzyFind(const FuzzyFindRequest &Req,
-                            function_ref<void(const Symbol &)> Callback) const {
+bool MergedIndex::fuzzyFind(
+    const FuzzyFindRequest &Req,
+    llvm::function_ref<void(const Symbol &)> Callback) const {
   // We can't step through both sources in parallel. So:
   //  1) query all dynamic symbols, slurping results into a slab
   //  2) query the static symbols, for each one:
@@ -43,7 +43,7 @@ bool MergedIndex::fuzzyFind(const FuzzyF
   });
   SymbolSlab Dyn = std::move(DynB).build();
 
-  DenseSet<SymbolID> SeenDynamicSymbols;
+  llvm::DenseSet<SymbolID> SeenDynamicSymbols;
   More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
     auto DynS = Dyn.find(S.ID);
     ++StaticCount;
@@ -62,8 +62,9 @@ bool MergedIndex::fuzzyFind(const FuzzyF
   return More;
 }
 
-void MergedIndex::lookup(const LookupRequest &Req,
-                         function_ref<void(const Symbol &)> Callback) const {
+void MergedIndex::lookup(
+    const LookupRequest &Req,
+    llvm::function_ref<void(const Symbol &)> Callback) const {
   trace::Span Tracer("MergedIndex lookup");
   SymbolSlab::Builder B;
 
@@ -84,7 +85,7 @@ void MergedIndex::lookup(const LookupReq
 }
 
 void MergedIndex::refs(const RefsRequest &Req,
-                       function_ref<void(const Ref &)> Callback) const {
+                       llvm::function_ref<void(const Ref &)> Callback) const {
   trace::Span Tracer("MergedIndex refs");
   // We don't want duplicated refs from the static/dynamic indexes,
   // and we can't reliably duplicate them because offsets may differ slightly.
@@ -94,7 +95,7 @@ void MergedIndex::refs(const RefsRequest
   // FIXME: The heuristic fails if the dynamic index contains a file, but all
   // refs were removed (we will report stale ones from the static index).
   // Ultimately we should explicit check which index has the file instead.
-  StringSet<> DynamicIndexFileURIs;
+  llvm::StringSet<> DynamicIndexFileURIs;
   Dynamic->refs(Req, [&](const Ref &O) {
     DynamicIndexFileURIs.insert(O.Location.FileURI);
     Callback(O);

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp Mon Jan  7 07:45:19 2019
@@ -17,12 +17,12 @@
 #include "llvm/Support/Endian.h"
 #include "llvm/Support/Error.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
-Error makeError(const Twine &Msg) {
-  return make_error<StringError>(Msg, inconvertibleErrorCode());
+llvm::Error makeError(const llvm::Twine &Msg) {
+  return llvm::make_error<llvm::StringError>(Msg,
+                                             llvm::inconvertibleErrorCode());
 }
 
 // IO PRIMITIVES
@@ -40,14 +40,14 @@ class Reader {
   bool Err = false;
 
 public:
-  Reader(StringRef Data) : Begin(Data.begin()), End(Data.end()) {}
+  Reader(llvm::StringRef Data) : Begin(Data.begin()), End(Data.end()) {}
   // The "error" bit is set by reading past EOF or reading invalid data.
   // When in an error state, reads may return zero values: callers should check.
   bool err() const { return Err; }
   // Did we read all the data, or encounter an error?
   bool eof() const { return Begin == End || Err; }
   // All the data we didn't read yet.
-  StringRef rest() const { return StringRef(Begin, End - Begin); }
+  llvm::StringRef rest() const { return llvm::StringRef(Begin, End - Begin); }
 
   uint8_t consume8() {
     if (LLVM_UNLIKELY(Begin == End)) {
@@ -62,17 +62,17 @@ public:
       Err = true;
       return 0;
     }
-    auto Ret = support::endian::read32le(Begin);
+    auto Ret = llvm::support::endian::read32le(Begin);
     Begin += 4;
     return Ret;
   }
 
-  StringRef consume(int N) {
+  llvm::StringRef consume(int N) {
     if (LLVM_UNLIKELY(Begin + N > End)) {
       Err = true;
-      return StringRef();
+      return llvm::StringRef();
     }
-    StringRef Ret(Begin, N);
+    llvm::StringRef Ret(Begin, N);
     Begin += N;
     return Ret;
   }
@@ -90,28 +90,28 @@ public:
     return Val;
   }
 
-  StringRef consumeString(ArrayRef<StringRef> Strings) {
+  llvm::StringRef consumeString(llvm::ArrayRef<llvm::StringRef> Strings) {
     auto StringIndex = consumeVar();
     if (LLVM_UNLIKELY(StringIndex >= Strings.size())) {
       Err = true;
-      return StringRef();
+      return llvm::StringRef();
     }
     return Strings[StringIndex];
   }
 
   SymbolID consumeID() {
-    StringRef Raw = consume(SymbolID::RawSize); // short if truncated.
+    llvm::StringRef Raw = consume(SymbolID::RawSize); // short if truncated.
     return LLVM_UNLIKELY(err()) ? SymbolID() : SymbolID::fromRaw(Raw);
   }
 };
 
-void write32(uint32_t I, raw_ostream &OS) {
+void write32(uint32_t I, llvm::raw_ostream &OS) {
   char buf[4];
-  support::endian::write32le(buf, I);
+  llvm::support::endian::write32le(buf, I);
   OS.write(buf, sizeof(buf));
 }
 
-void writeVar(uint32_t I, raw_ostream &OS) {
+void writeVar(uint32_t I, llvm::raw_ostream &OS) {
   constexpr static uint8_t More = 1 << 7;
   if (LLVM_LIKELY(I < 1 << 7)) {
     OS.write(I);
@@ -142,10 +142,10 @@ void writeVar(uint32_t I, raw_ostream &O
 // Maps each string to a canonical representation.
 // Strings remain owned externally (e.g. by SymbolSlab).
 class StringTableOut {
-  DenseSet<StringRef> Unique;
-  std::vector<StringRef> Sorted;
+  llvm::DenseSet<llvm::StringRef> Unique;
+  std::vector<llvm::StringRef> Sorted;
   // Since strings are interned, look up can be by pointer.
-  DenseMap<std::pair<const char *, size_t>, unsigned> Index;
+  llvm::DenseMap<std::pair<const char *, size_t>, unsigned> Index;
 
 public:
   StringTableOut() {
@@ -154,22 +154,22 @@ public:
     Unique.insert("");
   }
   // Add a string to the table. Overwrites S if an identical string exists.
-  void intern(StringRef &S) { S = *Unique.insert(S).first; };
+  void intern(llvm::StringRef &S) { S = *Unique.insert(S).first; };
   // Finalize the table and write it to OS. No more strings may be added.
-  void finalize(raw_ostream &OS) {
+  void finalize(llvm::raw_ostream &OS) {
     Sorted = {Unique.begin(), Unique.end()};
     llvm::sort(Sorted);
     for (unsigned I = 0; I < Sorted.size(); ++I)
       Index.try_emplace({Sorted[I].data(), Sorted[I].size()}, I);
 
     std::string RawTable;
-    for (StringRef S : Sorted) {
+    for (llvm::StringRef S : Sorted) {
       RawTable.append(S);
       RawTable.push_back(0);
     }
-    if (zlib::isAvailable()) {
-      SmallString<1> Compressed;
-      cantFail(zlib::compress(RawTable, Compressed));
+    if (llvm::zlib::isAvailable()) {
+      llvm::SmallString<1> Compressed;
+      llvm::cantFail(llvm::zlib::compress(RawTable, Compressed));
       write32(RawTable.size(), OS);
       OS << Compressed;
     } else {
@@ -178,7 +178,7 @@ public:
     }
   }
   // Get the ID of an string, which must be interned. Table must be finalized.
-  unsigned index(StringRef S) const {
+  unsigned index(llvm::StringRef S) const {
     assert(!Sorted.empty() && "table not finalized");
     assert(Index.count({S.data(), S.size()}) && "string not interned");
     return Index.find({S.data(), S.size()})->second;
@@ -186,33 +186,33 @@ public:
 };
 
 struct StringTableIn {
-  BumpPtrAllocator Arena;
-  std::vector<StringRef> Strings;
+  llvm::BumpPtrAllocator Arena;
+  std::vector<llvm::StringRef> Strings;
 };
 
-Expected<StringTableIn> readStringTable(StringRef Data) {
+llvm::Expected<StringTableIn> readStringTable(llvm::StringRef Data) {
   Reader R(Data);
   size_t UncompressedSize = R.consume32();
   if (R.err())
     return makeError("Truncated string table");
 
-  StringRef Uncompressed;
-  SmallString<1> UncompressedStorage;
+  llvm::StringRef Uncompressed;
+  llvm::SmallString<1> UncompressedStorage;
   if (UncompressedSize == 0) // No compression
     Uncompressed = R.rest();
   else {
-    if (Error E = llvm::zlib::uncompress(R.rest(), UncompressedStorage,
-                                         UncompressedSize))
+    if (llvm::Error E = llvm::zlib::uncompress(R.rest(), UncompressedStorage,
+                                               UncompressedSize))
       return std::move(E);
     Uncompressed = UncompressedStorage;
   }
 
   StringTableIn Table;
-  StringSaver Saver(Table.Arena);
+  llvm::StringSaver Saver(Table.Arena);
   R = Reader(Uncompressed);
   for (Reader R(Uncompressed); !R.eof();) {
     auto Len = R.rest().find(0);
-    if (Len == StringRef::npos)
+    if (Len == llvm::StringRef::npos)
       return makeError("Bad string table: not null terminated");
     Table.Strings.push_back(Saver.save(R.consume(Len)));
     R.consume8();
@@ -229,7 +229,7 @@ Expected<StringTableIn> readStringTable(
 //  - most numbers encode as varint
 
 void writeLocation(const SymbolLocation &Loc, const StringTableOut &Strings,
-                   raw_ostream &OS) {
+                   llvm::raw_ostream &OS) {
   writeVar(Strings.index(Loc.FileURI), OS);
   for (const auto &Endpoint : {Loc.Start, Loc.End}) {
     writeVar(Endpoint.line(), OS);
@@ -237,7 +237,8 @@ void writeLocation(const SymbolLocation
   }
 }
 
-SymbolLocation readLocation(Reader &Data, ArrayRef<StringRef> Strings) {
+SymbolLocation readLocation(Reader &Data,
+                            llvm::ArrayRef<llvm::StringRef> Strings) {
   SymbolLocation Loc;
   Loc.FileURI = Data.consumeString(Strings).data();
   for (auto *Endpoint : {&Loc.Start, &Loc.End}) {
@@ -261,7 +262,8 @@ IncludeGraphNode readIncludeGraphNode(Re
 }
 
 void writeIncludeGraphNode(const IncludeGraphNode &IGN,
-                           const StringTableOut &Strings, raw_ostream &OS) {
+                           const StringTableOut &Strings,
+                           llvm::raw_ostream &OS) {
   OS.write(IGN.IsTU);
   writeVar(Strings.index(IGN.URI), OS);
   llvm::StringRef Hash(reinterpret_cast<const char *>(IGN.Digest.data()),
@@ -273,7 +275,7 @@ void writeIncludeGraphNode(const Include
 }
 
 void writeSymbol(const Symbol &Sym, const StringTableOut &Strings,
-                 raw_ostream &OS) {
+                 llvm::raw_ostream &OS) {
   OS << Sym.ID.raw(); // TODO: once we start writing xrefs and posting lists,
                       // symbol IDs should probably be in a string table.
   OS.write(static_cast<uint8_t>(Sym.SymInfo.Kind));
@@ -300,7 +302,7 @@ void writeSymbol(const Symbol &Sym, cons
     WriteInclude(Include);
 }
 
-Symbol readSymbol(Reader &Data, ArrayRef<StringRef> Strings) {
+Symbol readSymbol(Reader &Data, llvm::ArrayRef<llvm::StringRef> Strings) {
   Symbol Sym;
   Sym.ID = Data.consumeID();
   Sym.SymInfo.Kind = static_cast<index::SymbolKind>(Data.consume8());
@@ -332,8 +334,8 @@ Symbol readSymbol(Reader &Data, ArrayRef
 //  - Ref[NumRefs]
 // Fields of Ref are encoded in turn, see implementation.
 
-void writeRefs(const SymbolID &ID, ArrayRef<Ref> Refs,
-               const StringTableOut &Strings, raw_ostream &OS) {
+void writeRefs(const SymbolID &ID, llvm::ArrayRef<Ref> Refs,
+               const StringTableOut &Strings, llvm::raw_ostream &OS) {
   OS << ID.raw();
   writeVar(Refs.size(), OS);
   for (const auto &Ref : Refs) {
@@ -342,8 +344,8 @@ void writeRefs(const SymbolID &ID, Array
   }
 }
 
-std::pair<SymbolID, std::vector<Ref>> readRefs(Reader &Data,
-                                               ArrayRef<StringRef> Strings) {
+std::pair<SymbolID, std::vector<Ref>>
+readRefs(Reader &Data, llvm::ArrayRef<llvm::StringRef> Strings) {
   std::pair<SymbolID, std::vector<Ref>> Result;
   Result.first = Data.consumeID();
   Result.second.resize(Data.consumeVar());
@@ -368,17 +370,18 @@ std::pair<SymbolID, std::vector<Ref>> re
 // data. Later we may want to support some backward compatibility.
 constexpr static uint32_t Version = 8;
 
-Expected<IndexFileIn> readRIFF(StringRef Data) {
+llvm::Expected<IndexFileIn> readRIFF(llvm::StringRef Data) {
   auto RIFF = riff::readFile(Data);
   if (!RIFF)
     return RIFF.takeError();
   if (RIFF->Type != riff::fourCC("CdIx"))
     return makeError("wrong RIFF type");
-  StringMap<StringRef> Chunks;
+  llvm::StringMap<llvm::StringRef> Chunks;
   for (const auto &Chunk : RIFF->Chunks)
-    Chunks.try_emplace(StringRef(Chunk.ID.data(), Chunk.ID.size()), Chunk.Data);
+    Chunks.try_emplace(llvm::StringRef(Chunk.ID.data(), Chunk.ID.size()),
+                       Chunk.Data);
 
-  for (StringRef RequiredChunk : {"meta", "stri"})
+  for (llvm::StringRef RequiredChunk : {"meta", "stri"})
     if (!Chunks.count(RequiredChunk))
       return makeError("missing required chunk " + RequiredChunk);
 
@@ -439,14 +442,14 @@ void visitStrings(IncludeGraphNode &IGN,
     CB(Include);
 }
 
-void writeRIFF(const IndexFileOut &Data, raw_ostream &OS) {
+void writeRIFF(const IndexFileOut &Data, llvm::raw_ostream &OS) {
   assert(Data.Symbols && "An index file without symbols makes no sense!");
   riff::File RIFF;
   RIFF.Type = riff::fourCC("CdIx");
 
-  SmallString<4> Meta;
+  llvm::SmallString<4> Meta;
   {
-    raw_svector_ostream MetaOS(Meta);
+    llvm::raw_svector_ostream MetaOS(Meta);
     write32(Version, MetaOS);
   }
   RIFF.Chunks.push_back({riff::fourCC("meta"), Meta});
@@ -455,13 +458,15 @@ void writeRIFF(const IndexFileOut &Data,
   std::vector<Symbol> Symbols;
   for (const auto &Sym : *Data.Symbols) {
     Symbols.emplace_back(Sym);
-    visitStrings(Symbols.back(), [&](StringRef &S) { Strings.intern(S); });
+    visitStrings(Symbols.back(),
+                 [&](llvm::StringRef &S) { Strings.intern(S); });
   }
   std::vector<IncludeGraphNode> Sources;
   if (Data.Sources)
     for (const auto &Source : *Data.Sources) {
       Sources.push_back(Source.getValue());
-      visitStrings(Sources.back(), [&](StringRef &S) { Strings.intern(S); });
+      visitStrings(Sources.back(),
+                   [&](llvm::StringRef &S) { Strings.intern(S); });
     }
 
   std::vector<std::pair<SymbolID, std::vector<Ref>>> Refs;
@@ -469,7 +474,7 @@ void writeRIFF(const IndexFileOut &Data,
     for (const auto &Sym : *Data.Refs) {
       Refs.emplace_back(Sym);
       for (auto &Ref : Refs.back().second) {
-        StringRef File = Ref.Location.FileURI;
+        llvm::StringRef File = Ref.Location.FileURI;
         Strings.intern(File);
         Ref.Location.FileURI = File.data();
       }
@@ -478,14 +483,14 @@ void writeRIFF(const IndexFileOut &Data,
 
   std::string StringSection;
   {
-    raw_string_ostream StringOS(StringSection);
+    llvm::raw_string_ostream StringOS(StringSection);
     Strings.finalize(StringOS);
   }
   RIFF.Chunks.push_back({riff::fourCC("stri"), StringSection});
 
   std::string SymbolSection;
   {
-    raw_string_ostream SymbolOS(SymbolSection);
+    llvm::raw_string_ostream SymbolOS(SymbolSection);
     for (const auto &Sym : Symbols)
       writeSymbol(Sym, Strings, SymbolOS);
   }
@@ -494,7 +499,7 @@ void writeRIFF(const IndexFileOut &Data,
   std::string RefsSection;
   if (Data.Refs) {
     {
-      raw_string_ostream RefsOS(RefsSection);
+      llvm::raw_string_ostream RefsOS(RefsSection);
       for (const auto &Sym : Refs)
         writeRefs(Sym.first, Sym.second, Strings, RefsOS);
     }
@@ -504,7 +509,7 @@ void writeRIFF(const IndexFileOut &Data,
   std::string SrcsSection;
   {
     {
-      raw_string_ostream SrcsOS(SrcsSection);
+      llvm::raw_string_ostream SrcsOS(SrcsSection);
       for (const auto &SF : Sources)
         writeIncludeGraphNode(SF, Strings, SrcsOS);
     }
@@ -517,10 +522,10 @@ void writeRIFF(const IndexFileOut &Data,
 } // namespace
 
 // Defined in YAMLSerialization.cpp.
-void writeYAML(const IndexFileOut &, raw_ostream &);
-Expected<IndexFileIn> readYAML(StringRef);
+void writeYAML(const IndexFileOut &, llvm::raw_ostream &);
+llvm::Expected<IndexFileIn> readYAML(llvm::StringRef);
 
-raw_ostream &operator<<(raw_ostream &OS, const IndexFileOut &O) {
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const IndexFileOut &O) {
   switch (O.Format) {
   case IndexFileFormat::RIFF:
     writeRIFF(O, OS);
@@ -532,22 +537,23 @@ raw_ostream &operator<<(raw_ostream &OS,
   return OS;
 }
 
-Expected<IndexFileIn> readIndexFile(StringRef Data) {
+llvm::Expected<IndexFileIn> readIndexFile(llvm::StringRef Data) {
   if (Data.startswith("RIFF")) {
     return readRIFF(Data);
   } else if (auto YAMLContents = readYAML(Data)) {
     return std::move(*YAMLContents);
   } else {
     return makeError("Not a RIFF file and failed to parse as YAML: " +
-                     toString(YAMLContents.takeError()));
+                     llvm::toString(YAMLContents.takeError()));
   }
 }
 
-std::unique_ptr<SymbolIndex> loadIndex(StringRef SymbolFilename, bool UseDex) {
+std::unique_ptr<SymbolIndex> loadIndex(llvm::StringRef SymbolFilename,
+                                       bool UseDex) {
   trace::Span OverallTracer("LoadIndex");
-  auto Buffer = MemoryBuffer::getFile(SymbolFilename);
+  auto Buffer = llvm::MemoryBuffer::getFile(SymbolFilename);
   if (!Buffer) {
-    errs() << "Can't open " << SymbolFilename << "\n";
+    llvm::errs() << "Can't open " << SymbolFilename << "\n";
     return nullptr;
   }
 
@@ -561,7 +567,7 @@ std::unique_ptr<SymbolIndex> loadIndex(S
       if (I->Refs)
         Refs = std::move(*I->Refs);
     } else {
-      errs() << "Bad Index: " << toString(I.takeError()) << "\n";
+      llvm::errs() << "Bad Index: " << llvm::toString(I.takeError()) << "\n";
       return nullptr;
     }
   }

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Mon Jan  7 07:45:19 2019
@@ -29,7 +29,6 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -60,9 +59,9 @@ std::string toURI(const SourceManager &S
   }
   // We don't perform is_absolute check in an else branch because makeAbsolute
   // might return a relative path on some InMemoryFileSystems.
-  if (!sys::path::is_absolute(AbsolutePath) && !Opts.FallbackDir.empty())
-    sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath);
-  sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
+  if (!llvm::sys::path::is_absolute(AbsolutePath) && !Opts.FallbackDir.empty())
+    llvm::sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath);
+  llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
   return URI::create(AbsolutePath).toString();
 }
 
@@ -102,7 +101,7 @@ bool isPrivateProtoDecl(const NamedDecl
   // will include OUTER_INNER and exclude some_enum_constant.
   // FIXME: the heuristic relies on naming style (i.e. no underscore in
   // user-defined names) and can be improved.
-  return (ND.getKind() != Decl::EnumConstant) || any_of(Name, islower);
+  return (ND.getKind() != Decl::EnumConstant) || llvm::any_of(Name, islower);
 }
 
 // We only collect #include paths for symbols that are suitable for global code
@@ -130,9 +129,9 @@ bool shouldCollectIncludePath(index::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.
-Optional<std::string> getIncludeHeader(StringRef QName, const SourceManager &SM,
-                                       SourceLocation Loc,
-                                       const SymbolCollector::Options &Opts) {
+llvm::Optional<std::string>
+getIncludeHeader(llvm::StringRef QName, const SourceManager &SM,
+                 SourceLocation Loc, const SymbolCollector::Options &Opts) {
   std::vector<std::string> Headers;
   // Collect the #include stack.
   while (true) {
@@ -148,7 +147,7 @@ Optional<std::string> getIncludeHeader(S
   }
   if (Headers.empty())
     return None;
-  StringRef Header = Headers[0];
+  llvm::StringRef Header = Headers[0];
   if (Opts.Includes) {
     Header = Opts.Includes->mapHeader(Headers, QName);
     if (Header.startswith("<") || Header.startswith("\""))
@@ -186,11 +185,11 @@ bool shouldIndexFile(const SourceManager
 }
 
 // Return the symbol location of the token at \p TokLoc.
-Optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc,
-                                          const SourceManager &SM,
-                                          const SymbolCollector::Options &Opts,
-                                          const clang::LangOptions &LangOpts,
-                                          std::string &FileURIStorage) {
+llvm::Optional<SymbolLocation>
+getTokenLocation(SourceLocation TokLoc, const SourceManager &SM,
+                 const SymbolCollector::Options &Opts,
+                 const clang::LangOptions &LangOpts,
+                 std::string &FileURIStorage) {
   auto Path = SM.getFilename(TokLoc);
   if (Path.empty())
     return None;
@@ -299,7 +298,7 @@ bool SymbolCollector::shouldCollectSymbo
 // Always return true to continue indexing.
 bool SymbolCollector::handleDeclOccurence(
     const Decl *D, index::SymbolRoleSet Roles,
-    ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc,
+    llvm::ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc,
     index::IndexDataConsumer::ASTNodeInfo ASTNode) {
   assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
   assert(CompletionAllocator && CompletionTUInfo);
@@ -461,8 +460,8 @@ void SymbolCollector::finish() {
   }
 
   const auto &SM = ASTCtx->getSourceManager();
-  DenseMap<FileID, std::string> URICache;
-  auto GetURI = [&](FileID FID) -> Optional<std::string> {
+  llvm::DenseMap<FileID, std::string> URICache;
+  auto GetURI = [&](FileID FID) -> llvm::Optional<std::string> {
     auto Found = URICache.find(FID);
     if (Found == URICache.end()) {
       if (auto *FileEntry = SM.getFileEntryForID(FID)) {

Modified: clang-tools-extra/trunk/clangd/index/SymbolID.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolID.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/SymbolID.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolID.cpp Mon Jan  7 07:45:19 2019
@@ -10,40 +10,42 @@
 #include "SymbolID.h"
 #include "llvm/Support/SHA1.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
-SymbolID::SymbolID(StringRef USR) {
-  auto Hash = llvm::SHA1::hash(arrayRefFromStringRef(USR));
+SymbolID::SymbolID(llvm::StringRef USR) {
+  auto Hash = llvm::SHA1::hash(llvm::arrayRefFromStringRef(USR));
   static_assert(sizeof(Hash) >= RawSize, "RawSize larger than SHA1");
   memcpy(HashValue.data(), Hash.data(), RawSize);
 }
 
 llvm::StringRef SymbolID::raw() const {
-  return StringRef(reinterpret_cast<const char *>(HashValue.data()), RawSize);
+  return llvm::StringRef(reinterpret_cast<const char *>(HashValue.data()),
+                         RawSize);
 }
 
-SymbolID SymbolID::fromRaw(StringRef Raw) {
+SymbolID SymbolID::fromRaw(llvm::StringRef Raw) {
   SymbolID ID;
   assert(Raw.size() == RawSize);
   memcpy(ID.HashValue.data(), Raw.data(), RawSize);
   return ID;
 }
 
-std::string SymbolID::str() const { return toHex(raw()); }
+std::string SymbolID::str() const { return llvm::toHex(raw()); }
 
-Expected<SymbolID> SymbolID::fromStr(StringRef Str) {
+llvm::Expected<SymbolID> SymbolID::fromStr(llvm::StringRef Str) {
   if (Str.size() != RawSize * 2)
-    return createStringError(inconvertibleErrorCode(), "Bad ID length");
+    return llvm::createStringError(llvm::inconvertibleErrorCode(),
+                                   "Bad ID length");
   for (char C : Str)
-    if (!isHexDigit(C))
-      return createStringError(inconvertibleErrorCode(), "Bad hex ID");
-  return fromRaw(fromHex(Str));
+    if (!llvm::isHexDigit(C))
+      return llvm::createStringError(llvm::inconvertibleErrorCode(),
+                                     "Bad hex ID");
+  return fromRaw(llvm::fromHex(Str));
 }
 
-raw_ostream &operator<<(raw_ostream &OS, const SymbolID &ID) {
-  return OS << toHex(ID.raw());
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const SymbolID &ID) {
+  return OS << llvm::toHex(ID.raw());
 }
 
 llvm::hash_code hash_value(const SymbolID &ID) {

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp Mon Jan  7 07:45:19 2019
@@ -28,8 +28,6 @@
 #include "llvm/Support/raw_ostream.h"
 #include <cstdint>
 
-using namespace llvm;
-
 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::clangd::Symbol::IncludeHeaderWithReferences)
 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::clangd::Ref)
 
@@ -38,8 +36,8 @@ using RefBundle =
     std::pair<clang::clangd::SymbolID, std::vector<clang::clangd::Ref>>;
 // This is a pale imitation of std::variant<Symbol, RefBundle>
 struct VariantEntry {
-  Optional<clang::clangd::Symbol> Symbol;
-  Optional<RefBundle> Refs;
+  llvm::Optional<clang::clangd::Symbol> Symbol;
+  llvm::Optional<RefBundle> Refs;
 };
 // A class helps YAML to serialize the 32-bit encoded position (Line&Column),
 // as YAMLIO can't directly map bitfields.
@@ -66,14 +64,14 @@ using clang::index::SymbolLanguage;
 struct NormalizedSymbolID {
   NormalizedSymbolID(IO &) {}
   NormalizedSymbolID(IO &, const SymbolID &ID) {
-    raw_string_ostream OS(HexString);
+    llvm::raw_string_ostream OS(HexString);
     OS << ID;
   }
 
   SymbolID denormalize(IO &I) {
     auto ID = SymbolID::fromStr(HexString);
     if (!ID) {
-      I.setError(toString(ID.takeError()));
+      I.setError(llvm::toString(ID.takeError()));
       return SymbolID();
     }
     return *ID;
@@ -294,8 +292,8 @@ template <> struct MappingTraits<Variant
 namespace clang {
 namespace clangd {
 
-void writeYAML(const IndexFileOut &O, raw_ostream &OS) {
-  yaml::Output Yout(OS);
+void writeYAML(const IndexFileOut &O, llvm::raw_ostream &OS) {
+  llvm::yaml::Output Yout(OS);
   for (const auto &Sym : *O.Symbols) {
     VariantEntry Entry;
     Entry.Symbol = Sym;
@@ -309,17 +307,18 @@ void writeYAML(const IndexFileOut &O, ra
     }
 }
 
-Expected<IndexFileIn> readYAML(StringRef Data) {
+llvm::Expected<IndexFileIn> readYAML(llvm::StringRef Data) {
   SymbolSlab::Builder Symbols;
   RefSlab::Builder Refs;
-  BumpPtrAllocator Arena; // store the underlying data of Position::FileURI.
-  UniqueStringSaver Strings(Arena);
-  yaml::Input Yin(Data, &Strings);
+  llvm::BumpPtrAllocator
+      Arena; // store the underlying data of Position::FileURI.
+  llvm::UniqueStringSaver Strings(Arena);
+  llvm::yaml::Input Yin(Data, &Strings);
   do {
     VariantEntry Variant;
     Yin >> Variant;
     if (Yin.error())
-      return errorCodeToError(Yin.error());
+      return llvm::errorCodeToError(Yin.error());
     if (Variant.Symbol)
       Symbols.insert(*Variant.Symbol);
     if (Variant.Refs)
@@ -336,20 +335,20 @@ Expected<IndexFileIn> readYAML(StringRef
 std::string toYAML(const Symbol &S) {
   std::string Buf;
   {
-    raw_string_ostream OS(Buf);
-    yaml::Output Yout(OS);
+    llvm::raw_string_ostream OS(Buf);
+    llvm::yaml::Output Yout(OS);
     Symbol Sym = S; // copy: Yout<< requires mutability.
     Yout << Sym;
   }
   return Buf;
 }
 
-std::string toYAML(const std::pair<SymbolID, ArrayRef<Ref>> &Data) {
+std::string toYAML(const std::pair<SymbolID, llvm::ArrayRef<Ref>> &Data) {
   RefBundle Refs = {Data.first, Data.second};
   std::string Buf;
   {
-    raw_string_ostream OS(Buf);
-    yaml::Output Yout(OS);
+    llvm::raw_string_ostream OS(Buf);
+    llvm::yaml::Output Yout(OS);
     Yout << Refs;
   }
   return Buf;

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/dex/Dex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Dex.cpp Mon Jan  7 07:45:19 2019
@@ -20,7 +20,6 @@
 #include <algorithm>
 #include <queue>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace dex {
@@ -50,7 +49,7 @@ std::vector<Token> generateSearchTokens(
   std::vector<Token> Result = generateIdentifierTrigrams(Sym.Name);
   Result.emplace_back(Token::Kind::Scope, Sym.Scope);
   // Skip token generation for symbols with unknown declaration location.
-  if (!StringRef(Sym.CanonicalDeclaration.FileURI).empty())
+  if (!llvm::StringRef(Sym.CanonicalDeclaration.FileURI).empty())
     for (const auto &ProximityURI :
          generateProximityURIs(Sym.CanonicalDeclaration.FileURI))
       Result.emplace_back(Token::Kind::ProximityURI, ProximityURI);
@@ -60,14 +59,14 @@ std::vector<Token> generateSearchTokens(
 }
 
 // Constructs BOOST iterators for Path Proximities.
-std::unique_ptr<Iterator>
-createFileProximityIterator(ArrayRef<std::string> ProximityPaths,
-                            const DenseMap<Token, PostingList> &InvertedIndex,
-                            const Corpus &Corpus) {
+std::unique_ptr<Iterator> createFileProximityIterator(
+    llvm::ArrayRef<std::string> ProximityPaths,
+    const llvm::DenseMap<Token, PostingList> &InvertedIndex,
+    const Corpus &Corpus) {
   std::vector<std::unique_ptr<Iterator>> BoostingIterators;
   // Deduplicate parent URIs extracted from the ProximityPaths.
-  StringSet<> ParentURIs;
-  StringMap<SourceParams> Sources;
+  llvm::StringSet<> ParentURIs;
+  llvm::StringMap<SourceParams> Sources;
   for (const auto &Path : ProximityPaths) {
     Sources[Path] = SourceParams();
     auto PathURI = URI::create(Path);
@@ -124,7 +123,7 @@ void Dex::buildIndex() {
   }
 
   // Populate TempInvertedIndex with lists for index symbols.
-  DenseMap<Token, std::vector<DocID>> TempInvertedIndex;
+  llvm::DenseMap<Token, std::vector<DocID>> TempInvertedIndex;
   for (DocID SymbolRank = 0; SymbolRank < Symbols.size(); ++SymbolRank) {
     const auto *Sym = Symbols[SymbolRank];
     for (const auto &Token : generateSearchTokens(*Sym))
@@ -147,7 +146,7 @@ std::unique_ptr<Iterator> Dex::iterator(
 /// while applying Callback to each symbol in the order of decreasing quality
 /// of the matched symbols.
 bool Dex::fuzzyFind(const FuzzyFindRequest &Req,
-                    function_ref<void(const Symbol &)> Callback) const {
+                    llvm::function_ref<void(const Symbol &)> Callback) const {
   assert(!StringRef(Req.Query).contains("::") &&
          "There must be no :: in query.");
   trace::Span Tracer("Dex fuzzyFind");
@@ -190,7 +189,7 @@ bool Dex::fuzzyFind(const FuzzyFindReque
   // FIXME(kbobyrev): Tune this ratio.
   if (Req.Limit)
     Root = Corpus.limit(move(Root), *Req.Limit * 100);
-  SPAN_ATTACH(Tracer, "query", to_string(*Root));
+  SPAN_ATTACH(Tracer, "query", llvm::to_string(*Root));
   vlog("Dex query tree: {0}", *Root);
 
   using IDAndScore = std::pair<DocID, float>;
@@ -204,7 +203,7 @@ bool Dex::fuzzyFind(const FuzzyFindReque
   for (const auto &IDAndScore : IDAndScores) {
     const DocID SymbolDocID = IDAndScore.first;
     const auto *Sym = Symbols[SymbolDocID];
-    const Optional<float> Score = Filter.match(Sym->Name);
+    const llvm::Optional<float> Score = Filter.match(Sym->Name);
     if (!Score)
       continue;
     // Combine Fuzzy Matching score, precomputed symbol quality and boosting
@@ -225,7 +224,7 @@ bool Dex::fuzzyFind(const FuzzyFindReque
 }
 
 void Dex::lookup(const LookupRequest &Req,
-                 function_ref<void(const Symbol &)> Callback) const {
+                 llvm::function_ref<void(const Symbol &)> Callback) const {
   trace::Span Tracer("Dex lookup");
   for (const auto &ID : Req.IDs) {
     auto I = LookupTable.find(ID);
@@ -235,7 +234,7 @@ void Dex::lookup(const LookupRequest &Re
 }
 
 void Dex::refs(const RefsRequest &Req,
-               function_ref<void(const Ref &)> Callback) const {
+               llvm::function_ref<void(const Ref &)> Callback) const {
   trace::Span Tracer("Dex refs");
   for (const auto &ID : Req.IDs)
     for (const auto &Ref : Refs.lookup(ID))
@@ -254,13 +253,13 @@ size_t Dex::estimateMemoryUsage() const
   return Bytes + BackingDataSize;
 }
 
-std::vector<std::string> generateProximityURIs(StringRef URIPath) {
+std::vector<std::string> generateProximityURIs(llvm::StringRef URIPath) {
   std::vector<std::string> Result;
   auto ParsedURI = URI::parse(URIPath);
   assert(ParsedURI &&
          "Non-empty argument of generateProximityURIs() should be a valid "
          "URI.");
-  StringRef Body = ParsedURI->body();
+  llvm::StringRef Body = ParsedURI->body();
   // FIXME(kbobyrev): Currently, this is a heuristic which defines the maximum
   // size of resulting vector. Some projects might want to have higher limit if
   // the file hierarchy is deeper. For the generic case, it would be useful to
@@ -273,7 +272,7 @@ std::vector<std::string> generateProximi
   while (!Body.empty() && --Limit > 0) {
     // FIXME(kbobyrev): Parsing and encoding path to URIs is not necessary and
     // could be optimized.
-    Body = sys::path::parent_path(Body, sys::path::Style::posix);
+    Body = llvm::sys::path::parent_path(Body, llvm::sys::path::Style::posix);
     URI TokenURI(ParsedURI->scheme(), ParsedURI->authority(), Body);
     if (!Body.empty())
       Result.emplace_back(TokenURI.toString());

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp Mon Jan  7 07:45:19 2019
@@ -13,7 +13,6 @@
 #include <cassert>
 #include <numeric>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace dex {
@@ -77,7 +76,7 @@ public:
   }
 
 private:
-  raw_ostream &dump(raw_ostream &OS) const override {
+  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
     OS << "(& ";
     auto Separator = "";
     for (const auto &Child : Children) {
@@ -198,7 +197,7 @@ public:
   }
 
 private:
-  raw_ostream &dump(raw_ostream &OS) const override {
+  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
     OS << "(| ";
     auto Separator = "";
     for (const auto &Child : Children) {
@@ -246,7 +245,9 @@ public:
   size_t estimateSize() const override { return Size; }
 
 private:
-  raw_ostream &dump(raw_ostream &OS) const override { return OS << "true"; }
+  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+    return OS << "true";
+  }
 
   DocID Index = 0;
   /// Size of the underlying virtual PostingList.
@@ -271,7 +272,9 @@ public:
   size_t estimateSize() const override { return 0; }
 
 private:
-  raw_ostream &dump(raw_ostream &OS) const override { return OS << "false"; }
+  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+    return OS << "false";
+  }
 };
 
 /// Boost iterator is a wrapper around its child which multiplies scores of
@@ -294,7 +297,7 @@ public:
   size_t estimateSize() const override { return Child->estimateSize(); }
 
 private:
-  raw_ostream &dump(raw_ostream &OS) const override {
+  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
     return OS << "(* " << Factor << ' ' << *Child << ')';
   }
 
@@ -334,7 +337,7 @@ public:
   }
 
 private:
-  raw_ostream &dump(raw_ostream &OS) const override {
+  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
     return OS << "(LIMIT " << Limit << " " << *Child << ')';
   }
 

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp Mon Jan  7 07:45:19 2019
@@ -13,7 +13,6 @@
 #include "llvm/Support/Error.h"
 #include "llvm/Support/MathExtras.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace dex {
@@ -24,7 +23,7 @@ namespace {
 /// them on-the-fly when the contents of chunk are to be seen.
 class ChunkIterator : public Iterator {
 public:
-  explicit ChunkIterator(const Token *Tok, ArrayRef<Chunk> Chunks)
+  explicit ChunkIterator(const Token *Tok, llvm::ArrayRef<Chunk> Chunks)
       : Tok(Tok), Chunks(Chunks), CurrentChunk(Chunks.begin()) {
     if (!Chunks.empty()) {
       DecompressedChunk = CurrentChunk->decompress();
@@ -71,7 +70,7 @@ public:
   }
 
 private:
-  raw_ostream &dump(raw_ostream &OS) const override {
+  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
     if (Tok != nullptr)
       return OS << *Tok;
     OS << '[';
@@ -113,13 +112,13 @@ private:
   }
 
   const Token *Tok;
-  ArrayRef<Chunk> Chunks;
+  llvm::ArrayRef<Chunk> Chunks;
   /// Iterator over chunks.
   /// If CurrentChunk is valid, then DecompressedChunk is
   /// CurrentChunk->decompress() and CurrentID is a valid (non-end) iterator
   /// into it.
   decltype(Chunks)::const_iterator CurrentChunk;
-  SmallVector<DocID, Chunk::PayloadSize + 1> DecompressedChunk;
+  llvm::SmallVector<DocID, Chunk::PayloadSize + 1> DecompressedChunk;
   /// Iterator over DecompressedChunk.
   decltype(DecompressedChunk)::iterator CurrentID;
 
@@ -130,11 +129,11 @@ static constexpr size_t 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, MutableArrayRef<uint8_t> &Payload) {
+bool encodeVByte(DocID Delta, llvm::MutableArrayRef<uint8_t> &Payload) {
   assert(Delta != 0 && "0 is not a valid PostingList delta.");
   // Calculate number of bytes Delta encoding would take by examining the
   // meaningful bits.
-  unsigned Width = 1 + findLastSet(Delta) / BitsPerEncodingByte;
+  unsigned Width = 1 + llvm::findLastSet(Delta) / BitsPerEncodingByte;
   if (Width > Payload.size())
     return false;
 
@@ -166,12 +165,12 @@ bool encodeVByte(DocID Delta, MutableArr
 /// DocIDs    42            47        7000
 /// gaps                    5         6958
 /// Encoding  (raw number)  00000101  10110110 00101110
-std::vector<Chunk> encodeStream(ArrayRef<DocID> Documents) {
+std::vector<Chunk> encodeStream(llvm::ArrayRef<DocID> Documents) {
   assert(!Documents.empty() && "Can't encode empty sequence.");
   std::vector<Chunk> Result;
   Result.emplace_back();
   DocID Last = Result.back().Head = Documents.front();
-  MutableArrayRef<uint8_t> RemainingPayload = Result.back().Payload;
+  llvm::MutableArrayRef<uint8_t> RemainingPayload = Result.back().Payload;
   for (DocID Doc : Documents.drop_front()) {
     if (!encodeVByte(Doc - Last, RemainingPayload)) { // didn't fit, flush chunk
       Result.emplace_back();
@@ -185,7 +184,7 @@ std::vector<Chunk> encodeStream(ArrayRef
 
 /// Reads variable length DocID from the buffer and updates the buffer size. If
 /// the stream is terminated, return None.
-Optional<DocID> readVByte(ArrayRef<uint8_t> &Bytes) {
+llvm::Optional<DocID> readVByte(llvm::ArrayRef<uint8_t> &Bytes) {
   if (Bytes.front() == 0 || Bytes.empty())
     return None;
   DocID Result = 0;
@@ -203,9 +202,9 @@ Optional<DocID> readVByte(ArrayRef<uint8
 
 } // namespace
 
-SmallVector<DocID, Chunk::PayloadSize + 1> Chunk::decompress() const {
-  SmallVector<DocID, Chunk::PayloadSize + 1> Result{Head};
-  ArrayRef<uint8_t> Bytes(Payload);
+llvm::SmallVector<DocID, Chunk::PayloadSize + 1> Chunk::decompress() const {
+  llvm::SmallVector<DocID, Chunk::PayloadSize + 1> Result{Head};
+  llvm::ArrayRef<uint8_t> Bytes(Payload);
   DocID Delta;
   for (DocID Current = Head; !Bytes.empty(); Current += Delta) {
     auto MaybeDelta = readVByte(Bytes);
@@ -214,10 +213,10 @@ SmallVector<DocID, Chunk::PayloadSize +
     Delta = *MaybeDelta;
     Result.push_back(Current + Delta);
   }
-  return SmallVector<DocID, Chunk::PayloadSize + 1>{Result};
+  return llvm::SmallVector<DocID, Chunk::PayloadSize + 1>{Result};
 }
 
-PostingList::PostingList(ArrayRef<DocID> Documents)
+PostingList::PostingList(llvm::ArrayRef<DocID> Documents)
     : Chunks(encodeStream(Documents)) {}
 
 std::unique_ptr<Iterator> PostingList::iterator(const Token *Tok) const {

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/dex/Trigram.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Trigram.cpp Mon Jan  7 07:45:19 2019
@@ -17,16 +17,15 @@
 #include <queue>
 #include <string>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace dex {
 
-std::vector<Token> generateIdentifierTrigrams(StringRef Identifier) {
+std::vector<Token> generateIdentifierTrigrams(llvm::StringRef Identifier) {
   // Apply fuzzy matching text segmentation.
   std::vector<CharRole> Roles(Identifier.size());
   calculateRoles(Identifier,
-                 makeMutableArrayRef(Roles.data(), Identifier.size()));
+                 llvm::makeMutableArrayRef(Roles.data(), Identifier.size()));
 
   std::string LowercaseIdentifier = Identifier.lower();
 
@@ -48,7 +47,7 @@ std::vector<Token> generateIdentifierTri
     }
   }
 
-  DenseSet<Token> UniqueTrigrams;
+  llvm::DenseSet<Token> UniqueTrigrams;
 
   auto Add = [&](std::string Chars) {
     UniqueTrigrams.insert(Token(Token::Kind::Trigram, Chars));
@@ -85,7 +84,7 @@ std::vector<Token> generateIdentifierTri
   return {UniqueTrigrams.begin(), UniqueTrigrams.end()};
 }
 
-std::vector<Token> generateQueryTrigrams(StringRef Query) {
+std::vector<Token> generateQueryTrigrams(llvm::StringRef Query) {
   if (Query.empty())
     return {};
   std::string LowercaseQuery = Query.lower();
@@ -94,9 +93,9 @@ std::vector<Token> generateQueryTrigrams
 
   // Apply fuzzy matching text segmentation.
   std::vector<CharRole> Roles(Query.size());
-  calculateRoles(Query, makeMutableArrayRef(Roles.data(), Query.size()));
+  calculateRoles(Query, llvm::makeMutableArrayRef(Roles.data(), Query.size()));
 
-  DenseSet<Token> UniqueTrigrams;
+  llvm::DenseSet<Token> UniqueTrigrams;
   std::string Chars;
   for (unsigned I = 0; I < Query.size(); ++I) {
     if (Roles[I] != Head && Roles[I] != Tail)

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/index/dex/dexp/Dexp.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/dexp/Dexp.cpp Mon Jan  7 07:45:19 2019
@@ -22,14 +22,13 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Signals.h"
 
-using namespace llvm;
-using namespace clang;
-using namespace clangd;
-
+namespace clang {
+namespace clangd {
 namespace {
 
-cl::opt<std::string> IndexPath("index-path", cl::desc("Path to the index"),
-                               cl::Positional, cl::Required);
+llvm::cl::opt<std::string> IndexPath("index-path",
+                                     llvm::cl::desc("Path to the index"),
+                                     llvm::cl::Positional, llvm::cl::Required);
 
 static const std::string Overview = R"(
 This is an **experimental** interactive tool to process user-provided search
@@ -40,16 +39,16 @@ and manually construct non-trivial test
 Type use "help" request to get information about the details.
 )";
 
-void reportTime(StringRef Name, function_ref<void()> F) {
+void reportTime(llvm::StringRef Name, llvm::function_ref<void()> F) {
   const auto TimerStart = std::chrono::high_resolution_clock::now();
   F();
   const auto TimerStop = std::chrono::high_resolution_clock::now();
   const auto Duration = std::chrono::duration_cast<std::chrono::milliseconds>(
       TimerStop - TimerStart);
-  outs() << formatv("{0} took {1:ms+n}.\n", Name, Duration);
+  llvm::outs() << llvm::formatv("{0} took {1:ms+n}.\n", Name, Duration);
 }
 
-std::vector<SymbolID> getSymbolIDsFromIndex(StringRef QualifiedName,
+std::vector<SymbolID> getSymbolIDsFromIndex(llvm::StringRef QualifiedName,
                                             const SymbolIndex *Index) {
   FuzzyFindRequest Request;
   // Remove leading "::" qualifier as FuzzyFind doesn't need leading "::"
@@ -77,9 +76,9 @@ std::vector<SymbolID> getSymbolIDsFromIn
 // Creating a Command populates parser options, parseAndRun() resets them.
 class Command {
   // By resetting the parser options, we lost the standard -help flag.
-  cl::opt<bool, false, cl::parser<bool>> Help{
-      "help", cl::desc("Display available options"), cl::ValueDisallowed,
-      cl::cat(cl::GeneralCategory)};
+  llvm::cl::opt<bool, false, llvm::cl::parser<bool>> Help{
+      "help", llvm::cl::desc("Display available options"),
+      llvm::cl::ValueDisallowed, llvm::cl::cat(llvm::cl::GeneralCategory)};
   virtual void run() = 0;
 
 protected:
@@ -87,24 +86,25 @@ protected:
 
 public:
   virtual ~Command() = default;
-  virtual void parseAndRun(ArrayRef<const char *> Argv, const char *Overview,
-                           const SymbolIndex &Index) {
+  virtual void parseAndRun(llvm::ArrayRef<const char *> Argv,
+                           const char *Overview, const SymbolIndex &Index) {
     std::string ParseErrs;
-    raw_string_ostream OS(ParseErrs);
-    bool Ok =
-        cl::ParseCommandLineOptions(Argv.size(), Argv.data(), Overview, &OS);
+    llvm::raw_string_ostream OS(ParseErrs);
+    bool Ok = llvm::cl::ParseCommandLineOptions(Argv.size(), Argv.data(),
+                                                Overview, &OS);
     if (Help.getNumOccurrences() > 0) {
       // Avoid printing parse errors in this case.
       // (Well, in theory. A bunch get printed to llvm::errs() regardless!)
-      cl::PrintHelpMessage();
+      llvm::cl::PrintHelpMessage();
     } else {
-      outs() << OS.str();
+      llvm::outs() << OS.str();
       if (Ok) {
         this->Index = &Index;
         reportTime(Argv[0], [&] { run(); });
       }
     }
-    cl::ResetCommandLineParser(); // must do this before opts are destroyed.
+    llvm::cl::ResetCommandLineParser(); // must do this before opts are
+                                        // destroyed.
   }
 };
 
@@ -118,20 +118,20 @@ public:
 // * print out tokens with least dense posting lists
 
 class FuzzyFind : public Command {
-  cl::opt<std::string> Query{
+  llvm::cl::opt<std::string> Query{
       "query",
-      cl::Positional,
-      cl::Required,
-      cl::desc("Query string to be fuzzy-matched"),
+      llvm::cl::Positional,
+      llvm::cl::Required,
+      llvm::cl::desc("Query string to be fuzzy-matched"),
   };
-  cl::opt<std::string> Scopes{
+  llvm::cl::opt<std::string> Scopes{
       "scopes",
-      cl::desc("Allowed symbol scopes (comma-separated list)"),
+      llvm::cl::desc("Allowed symbol scopes (comma-separated list)"),
   };
-  cl::opt<unsigned> Limit{
+  llvm::cl::opt<unsigned> Limit{
       "limit",
-      cl::init(10),
-      cl::desc("Max results to display"),
+      llvm::cl::init(10),
+      llvm::cl::desc("Max results to display"),
   };
 
   void run() override {
@@ -139,42 +139,45 @@ class FuzzyFind : public Command {
     Request.Limit = Limit;
     Request.Query = Query;
     if (Scopes.getNumOccurrences() > 0) {
-      SmallVector<StringRef, 8> Scopes;
-      StringRef(this->Scopes).split(Scopes, ',');
+      llvm::SmallVector<llvm::StringRef, 8> Scopes;
+      llvm::StringRef(this->Scopes).split(Scopes, ',');
       Request.Scopes = {Scopes.begin(), Scopes.end()};
     }
     Request.AnyScope = Request.Scopes.empty();
     // FIXME(kbobyrev): Print symbol final scores to see the distribution.
     static const auto OutputFormat = "{0,-4} | {1,-40} | {2,-25}\n";
-    outs() << formatv(OutputFormat, "Rank", "Symbol ID", "Symbol Name");
+    llvm::outs() << llvm::formatv(OutputFormat, "Rank", "Symbol ID",
+                                  "Symbol Name");
     size_t Rank = 0;
     Index->fuzzyFind(Request, [&](const Symbol &Sym) {
-      outs() << formatv(OutputFormat, Rank++, Sym.ID.str(),
-                        Sym.Scope + Sym.Name);
+      llvm::outs() << llvm::formatv(OutputFormat, Rank++, Sym.ID.str(),
+                                    Sym.Scope + Sym.Name);
     });
   }
 };
 
 class Lookup : public Command {
-  cl::opt<std::string> ID{
+  llvm::cl::opt<std::string> ID{
       "id",
-      cl::Positional,
-      cl::desc("Symbol ID to look up (hex)"),
+      llvm::cl::Positional,
+      llvm::cl::desc("Symbol ID to look up (hex)"),
   };
-  cl::opt<std::string> Name{
-      "name", cl::desc("Qualified name to look up."),
+  llvm::cl::opt<std::string> Name{
+      "name",
+      llvm::cl::desc("Qualified name to look up."),
   };
 
   void run() override {
     if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {
-      outs() << "Missing required argument: please provide id or -name.\n";
+      llvm::outs()
+          << "Missing required argument: please provide id or -name.\n";
       return;
     }
     std::vector<SymbolID> IDs;
     if (ID.getNumOccurrences()) {
       auto SID = SymbolID::fromStr(ID);
       if (!SID) {
-        outs() << toString(SID.takeError()) << "\n";
+        llvm::outs() << llvm::toString(SID.takeError()) << "\n";
         return;
       }
       IDs.push_back(*SID);
@@ -187,60 +190,65 @@ class Lookup : public Command {
     bool FoundSymbol = false;
     Index->lookup(Request, [&](const Symbol &Sym) {
       FoundSymbol = true;
-      outs() << toYAML(Sym);
+      llvm::outs() << toYAML(Sym);
     });
     if (!FoundSymbol)
-      outs() << "not found\n";
+      llvm::outs() << "not found\n";
   }
 };
 
 class Refs : public Command {
-  cl::opt<std::string> ID{
-      "id", cl::Positional,
-      cl::desc("Symbol ID of the symbol being queried (hex)."),
+  llvm::cl::opt<std::string> ID{
+      "id",
+      llvm::cl::Positional,
+      llvm::cl::desc("Symbol ID of the symbol being queried (hex)."),
   };
-  cl::opt<std::string> Name{
-      "name", cl::desc("Qualified name of the symbol being queried."),
+  llvm::cl::opt<std::string> Name{
+      "name",
+      llvm::cl::desc("Qualified name of the symbol being queried."),
   };
-  cl::opt<std::string> Filter{
-      "filter", cl::init(".*"),
-      cl::desc(
+  llvm::cl::opt<std::string> Filter{
+      "filter",
+      llvm::cl::init(".*"),
+      llvm::cl::desc(
           "Print all results from files matching this regular expression."),
   };
 
   void run() override {
     if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {
-      outs() << "Missing required argument: please provide id or -name.\n";
+      llvm::outs()
+          << "Missing required argument: please provide id or -name.\n";
       return;
     }
     std::vector<SymbolID> IDs;
     if (ID.getNumOccurrences()) {
       auto SID = SymbolID::fromStr(ID);
       if (!SID) {
-        outs() << toString(SID.takeError()) << "\n";
+        llvm::outs() << llvm::toString(SID.takeError()) << "\n";
         return;
       }
       IDs.push_back(*SID);
     } else {
       IDs = getSymbolIDsFromIndex(Name, Index);
       if (IDs.size() > 1) {
-        outs() << formatv("The name {0} is ambiguous, found {1} different "
-                          "symbols. Please use id flag to disambiguate.\n",
-                          Name, IDs.size());
+        llvm::outs() << llvm::formatv(
+            "The name {0} is ambiguous, found {1} different "
+            "symbols. Please use id flag to disambiguate.\n",
+            Name, IDs.size());
         return;
       }
     }
     RefsRequest RefRequest;
     RefRequest.IDs.insert(IDs.begin(), IDs.end());
-    Regex RegexFilter(Filter);
+    llvm::Regex RegexFilter(Filter);
     Index->refs(RefRequest, [&RegexFilter](const Ref &R) {
       auto U = URI::parse(R.Location.FileURI);
       if (!U) {
-        outs() << U.takeError();
+        llvm::outs() << U.takeError();
         return;
       }
       if (RegexFilter.match(U->body()))
-        outs() << R << "\n";
+        llvm::outs() << R << "\n";
     });
   }
 };
@@ -257,16 +265,20 @@ struct {
      llvm::make_unique<Refs>},
 };
 
-std::unique_ptr<SymbolIndex> openIndex(StringRef Index) {
+std::unique_ptr<SymbolIndex> openIndex(llvm::StringRef Index) {
   return loadIndex(Index, /*UseDex=*/true);
 }
 
 } // namespace
+} // namespace clangd
+} // namespace clang
 
 int main(int argc, const char *argv[]) {
-  cl::ParseCommandLineOptions(argc, argv, Overview);
-  cl::ResetCommandLineParser(); // We reuse it for REPL commands.
-  sys::PrintStackTraceOnErrorSignal(argv[0]);
+  using namespace clang::clangd;
+
+  llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
+  llvm::cl::ResetCommandLineParser(); // We reuse it for REPL commands.
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
   std::unique_ptr<SymbolIndex> Index;
   reportTime("Dex build", [&]() {
@@ -274,28 +286,29 @@ int main(int argc, const char *argv[]) {
   });
 
   if (!Index) {
-    outs() << "Failed to open the index.\n";
+    llvm::outs() << "Failed to open the index.\n";
     return -1;
   }
 
-  LineEditor LE("dexp");
+  llvm::LineEditor LE("dexp");
 
-  while (Optional<std::string> Request = LE.readLine()) {
+  while (llvm::Optional<std::string> Request = LE.readLine()) {
     // Split on spaces and add required null-termination.
     std::replace(Request->begin(), Request->end(), ' ', '\0');
-    SmallVector<StringRef, 8> Args;
-    StringRef(*Request).split(Args, '\0', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
+    llvm::SmallVector<llvm::StringRef, 8> Args;
+    llvm::StringRef(*Request).split(Args, '\0', /*MaxSplit=*/-1,
+                                    /*KeepEmpty=*/false);
     if (Args.empty())
       continue;
     if (Args.front() == "help") {
-      outs() << "dexp - Index explorer\nCommands:\n";
+      llvm::outs() << "dexp - Index explorer\nCommands:\n";
       for (const auto &C : CommandInfo)
-        outs() << formatv("{0,16} - {1}\n", C.Name, C.Description);
-      outs() << "Get detailed command help with e.g. `find -help`.\n";
+        llvm::outs() << llvm::formatv("{0,16} - {1}\n", C.Name, C.Description);
+      llvm::outs() << "Get detailed command help with e.g. `find -help`.\n";
       continue;
     }
-    SmallVector<const char *, 8> FakeArgv;
-    for (StringRef S : Args)
+    llvm::SmallVector<const char *, 8> FakeArgv;
+    for (llvm::StringRef S : Args)
       FakeArgv.push_back(S.data()); // Terminated by separator or end of string.
 
     bool Recognized = false;
@@ -307,7 +320,7 @@ int main(int argc, const char *argv[]) {
       }
     }
     if (!Recognized)
-      outs() << "Unknown command. Try 'help'.\n";
+      llvm::outs() << "Unknown command. Try 'help'.\n";
   }
 
   return 0;

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp (original)
+++ clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp Mon Jan  7 07:45:19 2019
@@ -22,20 +22,17 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Signals.h"
 
-using namespace llvm;
-using namespace clang::tooling;
-
 namespace clang {
 namespace clangd {
 namespace {
 
-static cl::opt<IndexFileFormat>
-    Format("format", cl::desc("Format of the index to be written"),
-           cl::values(clEnumValN(IndexFileFormat::YAML, "yaml",
-                                 "human-readable YAML format"),
-                      clEnumValN(IndexFileFormat::RIFF, "binary",
-                                 "binary RIFF format")),
-           cl::init(IndexFileFormat::RIFF));
+static llvm::cl::opt<IndexFileFormat>
+    Format("format", llvm::cl::desc("Format of the index to be written"),
+           llvm::cl::values(clEnumValN(IndexFileFormat::YAML, "yaml",
+                                       "human-readable YAML format"),
+                            clEnumValN(IndexFileFormat::RIFF, "binary",
+                                       "binary RIFF format")),
+           llvm::cl::init(IndexFileFormat::RIFF));
 
 class IndexActionFactory : public tooling::FrontendActionFactory {
 public:
@@ -86,7 +83,7 @@ private:
 } // namespace clang
 
 int main(int argc, const char **argv) {
-  sys::PrintStackTraceOnErrorSignal(argv[0]);
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
   const char *Overview = R"(
   Creates an index of symbol information etc in a whole project.
@@ -103,10 +100,10 @@ int main(int argc, const char **argv) {
   )";
 
   auto Executor = clang::tooling::createExecutorFromCommandLineArgs(
-      argc, argv, cl::GeneralCategory, Overview);
+      argc, argv, llvm::cl::GeneralCategory, Overview);
 
   if (!Executor) {
-    errs() << toString(Executor.takeError()) << "\n";
+    llvm::errs() << llvm::toString(Executor.takeError()) << "\n";
     return 1;
   }
 
@@ -115,12 +112,12 @@ int main(int argc, const char **argv) {
   auto Err = Executor->get()->execute(
       llvm::make_unique<clang::clangd::IndexActionFactory>(Data));
   if (Err) {
-    errs() << toString(std::move(Err)) << "\n";
+    llvm::errs() << llvm::toString(std::move(Err)) << "\n";
   }
 
   // Emit collected data.
   clang::clangd::IndexFileOut Out(Data);
   Out.Format = clang::clangd::Format;
-  outs() << Out;
+  llvm::outs() << Out;
   return 0;
 }

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp (original)
+++ clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp Mon Jan  7 07:45:19 2019
@@ -25,176 +25,181 @@
 #include <string>
 #include <thread>
 
-using namespace llvm;
-using namespace clang;
-using namespace clang::clangd;
-
+namespace clang {
+namespace clangd {
 // FIXME: remove this option when Dex is cheap enough.
-static cl::opt<bool> UseDex("use-dex-index",
-                            cl::desc("Use experimental Dex dynamic index."),
-                            cl::init(false), cl::Hidden);
+static llvm::cl::opt<bool>
+    UseDex("use-dex-index",
+           llvm::cl::desc("Use experimental Dex dynamic index."),
+           llvm::cl::init(false), llvm::cl::Hidden);
 
-static cl::opt<Path> CompileCommandsDir(
+static llvm::cl::opt<Path> CompileCommandsDir(
     "compile-commands-dir",
-    cl::desc("Specify a path to look for compile_commands.json. If path "
-             "is invalid, clangd will look in the current directory and "
-             "parent paths of each source file."));
-
-static cl::opt<unsigned>
-    WorkerThreadsCount("j", cl::desc("Number of async workers used by clangd"),
-                       cl::init(getDefaultAsyncThreadsCount()));
+    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()));
 
 // FIXME: also support "plain" style where signatures are always omitted.
 enum CompletionStyleFlag { Detailed, Bundled };
-static cl::opt<CompletionStyleFlag> CompletionStyle(
-    "completion-style", cl::desc("Granularity of code completion suggestions"),
-    cl::values(
+static llvm::cl::opt<CompletionStyleFlag> CompletionStyle(
+    "completion-style",
+    llvm::cl::desc("Granularity of code completion suggestions"),
+    llvm::cl::values(
         clEnumValN(Detailed, "detailed",
                    "One completion item for each semantically distinct "
                    "completion, with full type information."),
         clEnumValN(Bundled, "bundled",
                    "Similar completion items (e.g. function overloads) are "
                    "combined. Type information shown where possible.")),
-    cl::init(Detailed));
+    llvm::cl::init(Detailed));
 
 // FIXME: Flags are the wrong mechanism for user preferences.
 // We should probably read a dotfile or similar.
-static cl::opt<bool> IncludeIneligibleResults(
+static llvm::cl::opt<bool> IncludeIneligibleResults(
     "include-ineligible-results",
-    cl::desc("Include ineligible completion results (e.g. private members)"),
-    cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
-    cl::Hidden);
-
-static cl::opt<JSONStreamStyle> InputStyle(
-    "input-style", cl::desc("Input JSON stream encoding"),
-    cl::values(
+    llvm::cl::desc(
+        "Include ineligible completion results (e.g. private members)"),
+    llvm::cl::init(CodeCompleteOptions().IncludeIneligibleResults),
+    llvm::cl::Hidden);
+
+static llvm::cl::opt<JSONStreamStyle> InputStyle(
+    "input-style", llvm::cl::desc("Input JSON stream encoding"),
+    llvm::cl::values(
         clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
         clEnumValN(JSONStreamStyle::Delimited, "delimited",
                    "messages delimited by --- lines, with # comment support")),
-    cl::init(JSONStreamStyle::Standard));
-
-static cl::opt<bool> PrettyPrint("pretty", cl::desc("Pretty-print JSON output"),
-                                 cl::init(false));
+    llvm::cl::init(JSONStreamStyle::Standard));
 
-static cl::opt<Logger::Level> LogLevel(
-    "log", cl::desc("Verbosity of log messages written to stderr"),
-    cl::values(clEnumValN(Logger::Error, "error", "Error messages only"),
-               clEnumValN(Logger::Info, "info", "High level execution tracing"),
-               clEnumValN(Logger::Debug, "verbose", "Low level details")),
-    cl::init(Logger::Info));
+static llvm::cl::opt<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>
+static llvm::cl::opt<bool>
     Test("lit-test",
-         cl::desc("Abbreviation for -input-style=delimited -pretty "
-                  "-run-synchronously -enable-test-scheme. "
-                  "Intended to simplify lit tests."),
-         cl::init(false), cl::Hidden);
+         llvm::cl::desc("Abbreviation for -input-style=delimited -pretty "
+                        "-run-synchronously -enable-test-scheme. "
+                        "Intended to simplify lit tests."),
+         llvm::cl::init(false), llvm::cl::Hidden);
 
-static cl::opt<bool> EnableTestScheme(
+static llvm::cl::opt<bool> EnableTestScheme(
     "enable-test-uri-scheme",
-    cl::desc("Enable 'test:' URI scheme. Only use in lit tests."),
-    cl::init(false), cl::Hidden);
+    llvm::cl::desc("Enable 'test:' URI scheme. Only use in lit tests."),
+    llvm::cl::init(false), llvm::cl::Hidden);
 
 enum PCHStorageFlag { Disk, Memory };
-static cl::opt<PCHStorageFlag> PCHStorage(
+static llvm::cl::opt<PCHStorageFlag> PCHStorage(
     "pch-storage",
-    cl::desc("Storing PCHs in memory increases memory usages, but may "
-             "improve performance"),
-    cl::values(clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
-               clEnumValN(PCHStorageFlag::Memory, "memory",
-                          "store PCHs in memory")),
-    cl::init(PCHStorageFlag::Disk));
-
-static cl::opt<int>
-    LimitResults("limit-results",
-                 cl::desc("Limit the number of results returned by clangd. "
-                          "0 means no limit."),
-                 cl::init(100));
-
-static cl::opt<bool>
-    RunSynchronously("run-synchronously",
-                     cl::desc("Parse on main thread. If set, -j is ignored"),
-                     cl::init(false), cl::Hidden);
-
-static cl::opt<Path> ResourceDir("resource-dir",
-                                 cl::desc("Directory for system clang headers"),
-                                 cl::init(""), cl::Hidden);
+    llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
+                   "improve performance"),
+    llvm::cl::values(
+        clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
+        clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
+    llvm::cl::init(PCHStorageFlag::Disk));
+
+static llvm::cl::opt<int> LimitResults(
+    "limit-results",
+    llvm::cl::desc("Limit the number of results returned by clangd. "
+                   "0 means no limit."),
+    llvm::cl::init(100));
+
+static llvm::cl::opt<bool> RunSynchronously(
+    "run-synchronously",
+    llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
+    llvm::cl::init(false), llvm::cl::Hidden);
+
+static llvm::cl::opt<Path>
+    ResourceDir("resource-dir",
+                llvm::cl::desc("Directory for system clang headers"),
+                llvm::cl::init(""), llvm::cl::Hidden);
 
-static cl::opt<Path> InputMirrorFile(
+static llvm::cl::opt<Path> InputMirrorFile(
     "input-mirror-file",
-    cl::desc(
+    llvm::cl::desc(
         "Mirror all LSP input to the specified file. Useful for debugging."),
-    cl::init(""), cl::Hidden);
+    llvm::cl::init(""), llvm::cl::Hidden);
 
-static cl::opt<bool> EnableIndex(
+static llvm::cl::opt<bool> EnableIndex(
     "index",
-    cl::desc(
+    llvm::cl::desc(
         "Enable index-based features. By default, clangd maintains an index "
         "built from symbols in opened files. Global index support needs to "
         "enabled separatedly."),
-    cl::init(true), cl::Hidden);
+    llvm::cl::init(true), llvm::cl::Hidden);
 
-static cl::opt<bool> AllScopesCompletion(
+static llvm::cl::opt<bool> AllScopesCompletion(
     "all-scopes-completion",
-    cl::desc(
+    llvm::cl::desc(
         "If set to true, code completion will include index symbols that are "
         "not defined in the scopes (e.g. "
         "namespaces) visible from the code completion point. Such completions "
         "can insert scope qualifiers."),
-    cl::init(true));
+    llvm::cl::init(true));
 
-static cl::opt<bool>
-    ShowOrigins("debug-origin", cl::desc("Show origins of completion items"),
-                cl::init(clangd::CodeCompleteOptions().ShowOrigins),
-                cl::Hidden);
+static llvm::cl::opt<bool> ShowOrigins(
+    "debug-origin", llvm::cl::desc("Show origins of completion items"),
+    llvm::cl::init(CodeCompleteOptions().ShowOrigins), llvm::cl::Hidden);
 
-static cl::opt<bool> HeaderInsertionDecorators(
+static llvm::cl::opt<bool> HeaderInsertionDecorators(
     "header-insertion-decorators",
-    cl::desc("Prepend a circular dot or space before the completion "
-             "label, depending on whether "
-             "an include line will be inserted or not."),
-    cl::init(true));
+    llvm::cl::desc("Prepend a circular dot or space before the completion "
+                   "label, depending on whether "
+                   "an include line will be inserted or not."),
+    llvm::cl::init(true));
 
-static cl::opt<Path> IndexFile(
+static llvm::cl::opt<Path> IndexFile(
     "index-file",
-    cl::desc(
+    llvm::cl::desc(
         "Index file to build the static index. The file must have been created "
         "by a compatible clangd-index.\n"
         "WARNING: This option is experimental only, and will be removed "
         "eventually. Don't rely on it."),
-    cl::init(""), cl::Hidden);
+    llvm::cl::init(""), llvm::cl::Hidden);
 
-static cl::opt<bool> EnableBackgroundIndex(
+static llvm::cl::opt<bool> EnableBackgroundIndex(
     "background-index",
-    cl::desc("Index project code in the background and persist index on disk. "
-             "Experimental"),
-    cl::init(false), cl::Hidden);
+    llvm::cl::desc(
+        "Index project code in the background and persist index on disk. "
+        "Experimental"),
+    llvm::cl::init(false), llvm::cl::Hidden);
 
-static cl::opt<int> BackgroundIndexRebuildPeriod(
+static llvm::cl::opt<int> BackgroundIndexRebuildPeriod(
     "background-index-rebuild-period",
-    cl::desc(
+    llvm::cl::desc(
         "If set to non-zero, the background index rebuilds the symbol index "
         "periodically every X milliseconds; otherwise, the "
         "symbol index will be updated for each indexed file."),
-    cl::init(5000), cl::Hidden);
+    llvm::cl::init(5000), llvm::cl::Hidden);
 
 enum CompileArgsFrom { LSPCompileArgs, FilesystemCompileArgs };
-static cl::opt<CompileArgsFrom> CompileArgsFrom(
-    "compile_args_from", cl::desc("The source of compile commands"),
-    cl::values(clEnumValN(LSPCompileArgs, "lsp",
-                          "All compile commands come from LSP and "
-                          "'compile_commands.json' files are ignored"),
-               clEnumValN(FilesystemCompileArgs, "filesystem",
-                          "All compile commands come from the "
-                          "'compile_commands.json' files")),
-    cl::init(FilesystemCompileArgs), cl::Hidden);
+static 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<bool> EnableFunctionArgSnippets(
+static llvm::cl::opt<bool> EnableFunctionArgSnippets(
     "function-arg-placeholders",
-    cl::desc("When disabled, completions contain only parentheses for "
-             "function calls. When enabled, completions also contain "
-             "placeholders for method parameters."),
-    cl::init(clangd::CodeCompleteOptions().EnableFunctionArgSnippets));
+    llvm::cl::desc("When disabled, completions contain only parentheses for "
+                   "function calls. When enabled, completions also contain "
+                   "placeholders for method parameters."),
+    llvm::cl::init(CodeCompleteOptions().EnableFunctionArgSnippets));
 
 namespace {
 
@@ -204,17 +209,18 @@ namespace {
 /// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
 class TestScheme : public URIScheme {
 public:
-  Expected<std::string> getAbsolutePath(StringRef /*Authority*/, StringRef Body,
-                                        StringRef /*HintPath*/) const override {
+  llvm::Expected<std::string>
+  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
+                  llvm::StringRef /*HintPath*/) const override {
     using namespace llvm::sys;
     // Still require "/" in body to mimic file scheme, as we want lengths of an
     // equivalent URI in both schemes to be the same.
     if (!Body.startswith("/"))
-      return make_error<StringError>(
+      return llvm::make_error<llvm::StringError>(
           "Expect URI body to be an absolute path starting with '/': " + Body,
-          inconvertibleErrorCode());
+          llvm::inconvertibleErrorCode());
     Body = Body.ltrim('/');
-    SmallVector<char, 16> Path(Body.begin(), Body.end());
+    llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
     path::native(Path);
     auto Err = fs::make_absolute(TestScheme::TestDir, Path);
     if (Err)
@@ -222,15 +228,17 @@ public:
     return std::string(Path.begin(), Path.end());
   }
 
-  Expected<URI> uriFromAbsolutePath(StringRef AbsolutePath) const override {
-    StringRef Body = AbsolutePath;
+  llvm::Expected<URI>
+  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
+    llvm::StringRef Body = AbsolutePath;
     if (!Body.consume_front(TestScheme::TestDir)) {
-      return make_error<StringError>("Path " + AbsolutePath +
-                                         " doesn't start with root " + TestDir,
-                                     inconvertibleErrorCode());
+      return llvm::make_error<llvm::StringError>(
+          "Path " + AbsolutePath + " doesn't start with root " + TestDir,
+          llvm::inconvertibleErrorCode());
     }
 
-    return URI("test", /*Authority=*/"", sys::path::convert_to_slash(Body));
+    return URI("test", /*Authority=*/"",
+               llvm::sys::path::convert_to_slash(Body));
   }
 
 private:
@@ -243,14 +251,19 @@ const char TestScheme::TestDir[] = "C:\\
 const char TestScheme::TestDir[] = "/clangd-test";
 #endif
 
-}
+} // namespace
+} // namespace clangd
+} // namespace clang
 
 int main(int argc, char *argv[]) {
-  sys::PrintStackTraceOnErrorSignal(argv[0]);
-  cl::SetVersionPrinter([](raw_ostream &OS) {
+  using namespace clang;
+  using namespace clang::clangd;
+
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
+  llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
     OS << clang::getClangToolFullVersion("clangd") << "\n";
   });
-  cl::ParseCommandLineOptions(
+  llvm::cl::ParseCommandLineOptions(
       argc, argv,
       "clangd is a language server that provides IDE-like features to editors. "
       "\n\nIt should be used via an editor plugin rather than invoked "
@@ -270,26 +283,27 @@ int main(int argc, char *argv[]) {
   }
 
   if (!RunSynchronously && WorkerThreadsCount == 0) {
-    errs() << "A number of worker threads cannot be 0. Did you mean to "
-              "specify -run-synchronously?";
+    llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
+                    "specify -run-synchronously?";
     return 1;
   }
 
   if (RunSynchronously) {
     if (WorkerThreadsCount.getNumOccurrences())
-      errs() << "Ignoring -j because -run-synchronously is set.\n";
+      llvm::errs() << "Ignoring -j because -run-synchronously is set.\n";
     WorkerThreadsCount = 0;
   }
 
   // Validate command line arguments.
-  Optional<raw_fd_ostream> InputMirrorStream;
+  llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
   if (!InputMirrorFile.empty()) {
     std::error_code EC;
     InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
-                              sys::fs::FA_Read | sys::fs::FA_Write);
+                              llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
     if (EC) {
       InputMirrorStream.reset();
-      errs() << "Error while opening an input mirror file: " << EC.message();
+      llvm::errs() << "Error while opening an input mirror file: "
+                   << EC.message();
     } else {
       InputMirrorStream->SetUnbuffered();
     }
@@ -298,51 +312,52 @@ int main(int argc, char *argv[]) {
   // Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
   // trace flag in your editor's config is annoying, launching with
   // `CLANGD_TRACE=trace.json vim` is easier.
-  Optional<raw_fd_ostream> TraceStream;
+  llvm::Optional<llvm::raw_fd_ostream> TraceStream;
   std::unique_ptr<trace::EventTracer> Tracer;
   if (auto *TraceFile = getenv("CLANGD_TRACE")) {
     std::error_code EC;
     TraceStream.emplace(TraceFile, /*ref*/ EC,
-                        sys::fs::FA_Read | sys::fs::FA_Write);
+                        llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
     if (EC) {
       TraceStream.reset();
-      errs() << "Error while opening trace file " << TraceFile << ": "
-             << EC.message();
+      llvm::errs() << "Error while opening trace file " << TraceFile << ": "
+                   << EC.message();
     } else {
       Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
     }
   }
 
-  Optional<trace::Session> TracingSession;
+  llvm::Optional<trace::Session> TracingSession;
   if (Tracer)
     TracingSession.emplace(*Tracer);
 
   // Use buffered stream to stderr (we still flush each log message). Unbuffered
   // stream can cause significant (non-deterministic) latency for the logger.
-  errs().SetBuffered();
-  StreamLogger Logger(errs(), LogLevel);
-  clangd::LoggingSession LoggingSession(Logger);
+  llvm::errs().SetBuffered();
+  StreamLogger Logger(llvm::errs(), LogLevel);
+  LoggingSession LoggingSession(Logger);
 
   // If --compile-commands-dir arg was invoked, check value and override default
   // path.
-  Optional<Path> CompileCommandsDirPath;
+  llvm::Optional<Path> CompileCommandsDirPath;
   if (!CompileCommandsDir.empty()) {
-    if (sys::fs::exists(CompileCommandsDir)) {
+    if (llvm::sys::fs::exists(CompileCommandsDir)) {
       // We support passing both relative and absolute paths to the
       // --compile-commands-dir argument, but we assume the path is absolute in
       // the rest of clangd so we make sure the path is absolute before
       // continuing.
-      SmallString<128> Path(CompileCommandsDir);
-      if (std::error_code EC = sys::fs::make_absolute(Path)) {
-        errs() << "Error while converting the relative path specified by "
-                  "--compile-commands-dir to an absolute path: "
-               << EC.message() << ". The argument will be ignored.\n";
+      llvm::SmallString<128> Path(CompileCommandsDir);
+      if (std::error_code EC = llvm::sys::fs::make_absolute(Path)) {
+        llvm::errs() << "Error while converting the relative path specified by "
+                        "--compile-commands-dir to an absolute path: "
+                     << EC.message() << ". The argument will be ignored.\n";
       } else {
         CompileCommandsDirPath = Path.str();
       }
     } else {
-      errs() << "Path specified by --compile-commands-dir does not exist. The "
-                "argument will be ignored.\n";
+      llvm::errs()
+          << "Path specified by --compile-commands-dir does not exist. The "
+             "argument will be ignored.\n";
     }
   }
 
@@ -392,15 +407,15 @@ int main(int argc, char *argv[]) {
 
   // Initialize and run ClangdLSPServer.
   // Change stdin to binary to not lose \r\n on windows.
-  sys::ChangeStdinToBinary();
+  llvm::sys::ChangeStdinToBinary();
   auto Transport = newJSONTransport(
-      stdin, outs(),
+      stdin, llvm::outs(),
       InputMirrorStream ? InputMirrorStream.getPointer() : nullptr, PrettyPrint,
       InputStyle);
   ClangdLSPServer LSPServer(
       *Transport, CCOpts, CompileCommandsDirPath,
       /*UseDirBasedCDB=*/CompileArgsFrom == FilesystemCompileArgs, Opts);
   constexpr int NoShutdownRequestErrorCode = 1;
-  set_thread_name("clangd.main");
+  llvm::set_thread_name("clangd.main");
   return LSPServer.run() ? 0 : NoShutdownRequestErrorCode;
 }

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/Annotations.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/Annotations.cpp Mon Jan  7 07:45:19 2019
@@ -10,26 +10,25 @@
 #include "Annotations.h"
 #include "SourceCode.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
 // 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, StringRef Code) {
+static void require(bool Assertion, const char *Msg, llvm::StringRef Code) {
   if (!Assertion) {
-    errs() << "Annotated testcase: " << Msg << "\n" << Code << "\n";
+    llvm::errs() << "Annotated testcase: " << Msg << "\n" << Code << "\n";
     llvm_unreachable("Annotated testcase assertion failed!");
   }
 }
 
-Annotations::Annotations(StringRef Text) {
+Annotations::Annotations(llvm::StringRef Text) {
   auto Here = [this] { return offsetToPosition(Code, Code.size()); };
   auto Require = [Text](bool Assertion, const char *Msg) {
     require(Assertion, Msg, Text);
   };
-  Optional<StringRef> Name;
-  SmallVector<std::pair<StringRef, Position>, 8> OpenRanges;
+  llvm::Optional<llvm::StringRef> Name;
+  llvm::SmallVector<std::pair<llvm::StringRef, Position>, 8> OpenRanges;
 
   Code.reserve(Text.size());
   while (!Text.empty()) {
@@ -52,7 +51,7 @@ Annotations::Annotations(StringRef Text)
       continue;
     }
     if (Text.consume_front("$")) {
-      Name = Text.take_while(isAlnum);
+      Name = Text.take_while(llvm::isAlnum);
       Text = Text.drop_front(Name->size());
       continue;
     }
@@ -63,23 +62,23 @@ Annotations::Annotations(StringRef Text)
   Require(OpenRanges.empty(), "unmatched [[");
 }
 
-Position Annotations::point(StringRef Name) const {
+Position Annotations::point(llvm::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(StringRef Name) const {
+std::vector<Position> Annotations::points(llvm::StringRef Name) const {
   auto P = Points.lookup(Name);
   return {P.begin(), P.end()};
 }
-Range Annotations::range(StringRef Name) const {
+Range Annotations::range(llvm::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(StringRef Name) const {
+std::vector<Range> Annotations::ranges(llvm::StringRef Name) const {
   auto R = Ranges.lookup(Name);
   return {R.begin(), R.end()};
 }

Modified: clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp Mon Jan  7 07:45:19 2019
@@ -13,7 +13,6 @@ using testing::ElementsAre;
 using testing::Not;
 using testing::UnorderedElementsAre;
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/CancellationTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/CancellationTests.cpp Mon Jan  7 07:45:19 2019
@@ -8,7 +8,6 @@
 #include <memory>
 #include <thread>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -22,7 +21,7 @@ TEST(CancellationTest, CancellationTest)
 }
 
 TEST(CancellationTest, CancelerDiesContextLives) {
-  Optional<WithContext> ContextWithCancellation;
+  llvm::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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp Mon Jan  7 07:45:19 2019
@@ -30,7 +30,6 @@
 #include <thread>
 #include <vector>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -109,14 +108,14 @@ public:
 
 private:
   mutable std::mutex Mutex;
-  StringMap<bool> LastDiagsHadError;
+  llvm::StringMap<bool> LastDiagsHadError;
 };
 
 /// Replaces all patterns of the form 0x123abc with spaces
 std::string replacePtrsInDump(std::string const &Dump) {
-  Regex RE("0x[0-9a-fA-F]+");
-  SmallVector<StringRef, 1> Matches;
-  StringRef Pending = Dump;
+  llvm::Regex RE("0x[0-9a-fA-F]+");
+  llvm::SmallVector<llvm::StringRef, 1> Matches;
+  llvm::StringRef Pending = Dump;
 
   std::string Result;
   while (RE.match(Pending, &Matches)) {
@@ -139,8 +138,8 @@ std::string dumpASTWithoutMemoryLocs(Cla
 class ClangdVFSTest : public ::testing::Test {
 protected:
   std::string parseSourceAndDumpAST(
-      PathRef SourceFileRelPath, StringRef SourceContents,
-      std::vector<std::pair<PathRef, StringRef>> ExtraFiles = {},
+      PathRef SourceFileRelPath, llvm::StringRef SourceContents,
+      std::vector<std::pair<PathRef, llvm::StringRef>> ExtraFiles = {},
       bool ExpectErrors = false) {
     MockFSProvider FS;
     ErrorCheckingDiagConsumer DiagConsumer;
@@ -269,7 +268,7 @@ int b = a;
 TEST_F(ClangdVFSTest, PropagatesContexts) {
   static Key<int> Secret;
   struct FSProvider : public FileSystemProvider {
-    IntrusiveRefCntPtr<vfs::FileSystem> getFileSystem() const override {
+    IntrusiveRefCntPtr<llvm::vfs::FileSystem> getFileSystem() const override {
       Got = Context::current().getExisting(Secret);
       return buildTestFS({});
     }
@@ -313,19 +312,19 @@ TEST_F(ClangdVFSTest, SearchLibDir) {
 
   // A lib dir for gcc installation
   SmallString<64> LibDir("/randomusr/lib/gcc/x86_64-linux-gnu");
-  sys::path::append(LibDir, Version);
+  llvm::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;
-  sys::path::append(DummyLibFile, LibDir, "64", "crtbegin.o");
+  llvm::sys::path::append(DummyLibFile, LibDir, "64", "crtbegin.o");
   FS.Files[DummyLibFile] = "";
 
   SmallString<64> IncludeDir("/randomusr/include/c++");
-  sys::path::append(IncludeDir, Version);
+  llvm::sys::path::append(IncludeDir, Version);
 
   SmallString<64> StringPath;
-  sys::path::append(StringPath, IncludeDir, "string");
+  llvm::sys::path::append(StringPath, IncludeDir, "string");
   FS.Files[StringPath] = "class mock_string {};";
 
   auto FooCpp = testPath("foo.cpp");
@@ -598,7 +597,7 @@ int d;
 
     void onDiagnosticsReady(PathRef File,
                             std::vector<Diag> Diagnostics) override {
-      StringRef FileIndexStr = sys::path::stem(File);
+      StringRef FileIndexStr = llvm::sys::path::stem(File);
       ASSERT_TRUE(FileIndexStr.consume_front("Foo"));
 
       unsigned long FileIndex = std::stoul(FileIndexStr.str());
@@ -976,28 +975,28 @@ TEST_F(ClangdVFSTest, ChangedHeaderFromI
 TEST(ClangdTests, PreambleVFSStatCache) {
   class ListenStatsFSProvider : public FileSystemProvider {
   public:
-    ListenStatsFSProvider(StringMap<unsigned> &CountStats)
+    ListenStatsFSProvider(llvm::StringMap<unsigned> &CountStats)
         : CountStats(CountStats) {}
 
-    IntrusiveRefCntPtr<vfs::FileSystem> getFileSystem() const override {
-      class ListenStatVFS : public vfs::ProxyFileSystem {
+    IntrusiveRefCntPtr<llvm::vfs::FileSystem> getFileSystem() const override {
+      class ListenStatVFS : public llvm::vfs::ProxyFileSystem {
       public:
-        ListenStatVFS(IntrusiveRefCntPtr<vfs::FileSystem> FS,
-                      StringMap<unsigned> &CountStats)
+        ListenStatVFS(IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
+                      llvm::StringMap<unsigned> &CountStats)
             : ProxyFileSystem(std::move(FS)), CountStats(CountStats) {}
 
-        ErrorOr<std::unique_ptr<vfs::File>>
+        llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
         openFileForRead(const Twine &Path) override {
-          ++CountStats[sys::path::filename(Path.str())];
+          ++CountStats[llvm::sys::path::filename(Path.str())];
           return ProxyFileSystem::openFileForRead(Path);
         }
-        ErrorOr<vfs::Status> status(const Twine &Path) override {
-          ++CountStats[sys::path::filename(Path.str())];
+        llvm::ErrorOr<llvm::vfs::Status> status(const Twine &Path) override {
+          ++CountStats[llvm::sys::path::filename(Path.str())];
           return ProxyFileSystem::status(Path);
         }
 
       private:
-        StringMap<unsigned> &CountStats;
+        llvm::StringMap<unsigned> &CountStats;
       };
 
       return IntrusiveRefCntPtr<ListenStatVFS>(
@@ -1005,11 +1004,11 @@ TEST(ClangdTests, PreambleVFSStatCache)
     }
 
     // If relative paths are used, they are resolved with testPath().
-    StringMap<std::string> Files;
-    StringMap<unsigned> &CountStats;
+    llvm::StringMap<std::string> Files;
+    llvm::StringMap<unsigned> &CountStats;
   };
 
-  StringMap<unsigned> CountStats;
+  llvm::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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp Mon Jan  7 07:45:19 2019
@@ -15,7 +15,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -35,23 +34,24 @@ testing::Matcher<const Diag &> WithNote(
 }
 
 MATCHER_P2(Diag, Range, Message,
-           "Diag at " + to_string(Range) + " = [" + Message + "]") {
+           "Diag at " + llvm::to_string(Range) + " = [" + Message + "]") {
   return arg.Range == Range && arg.Message == Message;
 }
 
 MATCHER_P3(Fix, Range, Replacement, Message,
-           "Fix " + to_string(Range) + " => " +
+           "Fix " + llvm::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 " + to_string(LSPDiag)) {
+MATCHER_P(EqualToLSPDiag, LSPDiag,
+          "LSP diagnostic " + llvm::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 " + to_string(Fix)) {
+MATCHER_P(EqualToFix, Fix, "LSP fix " + llvm::to_string(Fix)) {
   if (arg.Message != Fix.Message)
     return false;
   if (arg.Edits.size() != Fix.Edits.size())

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp Mon Jan  7 07:45:19 2019
@@ -24,11 +24,11 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
 namespace {
+using ::llvm::Failed;
 using ::testing::AllOf;
 using ::testing::Contains;
 using ::testing::Each;
@@ -87,7 +87,7 @@ std::unique_ptr<SymbolIndex> memIndex(st
   return MemIndex::build(std::move(Slab).build(), RefSlab());
 }
 
-CodeCompleteResult completions(ClangdServer &Server, StringRef TestCode,
+CodeCompleteResult completions(ClangdServer &Server, llvm::StringRef TestCode,
                                Position point,
                                std::vector<Symbol> IndexSymbols = {},
                                clangd::CodeCompleteOptions Opts = {}) {
@@ -100,11 +100,12 @@ CodeCompleteResult completions(ClangdSer
 
   auto File = testPath("foo.cpp");
   runAddDocument(Server, File, TestCode);
-  auto CompletionList = cantFail(runCodeComplete(Server, File, point, Opts));
+  auto CompletionList =
+      llvm::cantFail(runCodeComplete(Server, File, point, Opts));
   return CompletionList;
 }
 
-CodeCompleteResult completions(ClangdServer &Server, StringRef Text,
+CodeCompleteResult completions(ClangdServer &Server, llvm::StringRef Text,
                                std::vector<Symbol> IndexSymbols = {},
                                clangd::CodeCompleteOptions Opts = {},
                                PathRef FilePath = "foo.cpp") {
@@ -119,13 +120,13 @@ CodeCompleteResult completions(ClangdSer
   Annotations Test(Text);
   runAddDocument(Server, File, Test.code());
   auto CompletionList =
-      cantFail(runCodeComplete(Server, File, Test.point(), Opts));
+      llvm::cantFail(runCodeComplete(Server, File, Test.point(), Opts));
   return CompletionList;
 }
 
 // Builds a server and runs code completion.
 // If IndexSymbols is non-empty, an index will be built and passed to opts.
-CodeCompleteResult completions(StringRef Text,
+CodeCompleteResult completions(llvm::StringRef Text,
                                std::vector<Symbol> IndexSymbols = {},
                                clangd::CodeCompleteOptions Opts = {},
                                PathRef FilePath = "foo.cpp") {
@@ -137,10 +138,11 @@ CodeCompleteResult completions(StringRef
                      FilePath);
 }
 
-std::string replace(StringRef Haystack, StringRef Needle, StringRef Repl) {
+std::string replace(llvm::StringRef Haystack, llvm::StringRef Needle,
+                    llvm::StringRef Repl) {
   std::string Result;
-  raw_string_ostream OS(Result);
-  std::pair<StringRef, StringRef> Split;
+  llvm::raw_string_ostream OS(Result);
+  std::pair<llvm::StringRef, llvm::StringRef> Split;
   for (Split = Haystack.split(Needle); !Split.second.empty();
        Split = Split.first.split(Needle))
     OS << Split.first << Repl;
@@ -151,11 +153,12 @@ std::string replace(StringRef Haystack,
 
 // Helpers to produce fake index symbols for memIndex() or completions().
 // USRFormat is a regex replacement string for the unqualified part of the USR.
-Symbol sym(StringRef QName, index::SymbolKind Kind, StringRef USRFormat) {
+Symbol sym(llvm::StringRef QName, index::SymbolKind Kind,
+           llvm::StringRef USRFormat) {
   Symbol Sym;
   std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
   size_t Pos = QName.rfind("::");
-  if (Pos == StringRef::npos) {
+  if (Pos == llvm::StringRef::npos) {
     Sym.Name = QName;
     Sym.Scope = "";
   } else {
@@ -163,23 +166,23 @@ Symbol sym(StringRef QName, index::Symbo
     Sym.Scope = QName.substr(0, Pos + 2);
     USR += "@N@" + replace(QName.substr(0, Pos), "::", "@N@"); // ns:: -> @N at ns
   }
-  USR += Regex("^.*$").sub(USRFormat, Sym.Name); // e.g. func -> @F at func#
+  USR += llvm::Regex("^.*$").sub(USRFormat, Sym.Name); // e.g. func -> @F at func#
   Sym.ID = SymbolID(USR);
   Sym.SymInfo.Kind = Kind;
   Sym.Flags |= Symbol::IndexedForCodeCompletion;
   Sym.Origin = SymbolOrigin::Static;
   return Sym;
 }
-Symbol func(StringRef Name) { // Assumes the function has no args.
+Symbol func(llvm::StringRef Name) { // Assumes the function has no args.
   return sym(Name, index::SymbolKind::Function, "@F@\\0#"); // no args
 }
-Symbol cls(StringRef Name) {
+Symbol cls(llvm::StringRef Name) {
   return sym(Name, index::SymbolKind::Class, "@S@\\0");
 }
-Symbol var(StringRef Name) {
+Symbol var(llvm::StringRef Name) {
   return sym(Name, index::SymbolKind::Variable, "@\\0");
 }
-Symbol ns(StringRef Name) {
+Symbol ns(llvm::StringRef Name) {
   return sym(Name, index::SymbolKind::Namespace, "@N@\\0");
 }
 Symbol withReferences(int N, Symbol S) {
@@ -862,7 +865,7 @@ TEST(CompletionTest, IgnoreCompleteInExc
 
   EXPECT_TRUE(Results.Completions.empty());
 }
-SignatureHelp signatures(StringRef Text, Position Point,
+SignatureHelp signatures(llvm::StringRef Text, Position Point,
                          std::vector<Symbol> IndexSymbols = {}) {
   std::unique_ptr<SymbolIndex> Index;
   if (!IndexSymbols.empty())
@@ -877,10 +880,10 @@ SignatureHelp signatures(StringRef Text,
   ClangdServer Server(CDB, FS, DiagConsumer, Opts);
   auto File = testPath("foo.cpp");
   runAddDocument(Server, File, Text);
-  return cantFail(runSignatureHelp(Server, File, Point));
+  return llvm::cantFail(runSignatureHelp(Server, File, Point));
 }
 
-SignatureHelp signatures(StringRef Text,
+SignatureHelp signatures(llvm::StringRef Text,
                          std::vector<Symbol> IndexSymbols = {}) {
   Annotations Test(Text);
   return signatures(Test.code(), Test.point(), std::move(IndexSymbols));
@@ -998,18 +1001,19 @@ TEST(SignatureHelpTest, OpeningParen) {
 
 class IndexRequestCollector : public SymbolIndex {
 public:
-  bool fuzzyFind(const FuzzyFindRequest &Req,
-                 function_ref<void(const Symbol &)> Callback) const override {
+  bool
+  fuzzyFind(const FuzzyFindRequest &Req,
+            llvm::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 &,
-              function_ref<void(const Symbol &)>) const override {}
+              llvm::function_ref<void(const Symbol &)>) const override {}
 
   void refs(const RefsRequest &,
-            function_ref<void(const Ref &)>) const override {}
+            llvm::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.
@@ -1028,7 +1032,7 @@ private:
   mutable std::vector<FuzzyFindRequest> Requests;
 };
 
-std::vector<FuzzyFindRequest> captureIndexRequests(StringRef Code) {
+std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code) {
   clangd::CodeCompleteOptions Opts;
   IndexRequestCollector Requests;
   Opts.Index = &Requests;

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/DexTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/DexTests.cpp Mon Jan  7 07:45:19 2019
@@ -27,7 +27,6 @@ using ::testing::AnyOf;
 using ::testing::ElementsAre;
 using ::testing::UnorderedElementsAre;
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace dex {
@@ -248,17 +247,17 @@ TEST(DexIterators, StringRepresentation)
 
   // No token given, prints full posting list.
   auto I1 = L1.iterator();
-  EXPECT_EQ(to_string(*I1), "[1 3 5]");
+  EXPECT_EQ(llvm::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(to_string(*I2), "T=L2");
+  EXPECT_EQ(llvm::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(to_string(*Tree), AnyOf("(LIMIT 10 (& [1 3 5] T=L2))",
-                                      "(LIMIT 10 (& T=L2 [1 3 5]))"));
+  EXPECT_THAT(llvm::to_string(*Tree), AnyOf("(LIMIT 10 (& [1 3 5] T=L2))",
+                                            "(LIMIT 10 (& T=L2 [1 3 5]))"));
 }
 
 TEST(DexIterators, Limit) {
@@ -323,27 +322,28 @@ TEST(DexIterators, Optimizations) {
   const PostingList L3{3};
 
   // empty and/or yield true/false
-  EXPECT_EQ(to_string(*C.intersect()), "true");
-  EXPECT_EQ(to_string(*C.unionOf()), "false");
+  EXPECT_EQ(llvm::to_string(*C.intersect()), "true");
+  EXPECT_EQ(llvm::to_string(*C.unionOf()), "false");
 
   // true/false inside and/or short-circuit
-  EXPECT_EQ(to_string(*C.intersect(L1.iterator(), C.all())), "[1]");
-  EXPECT_EQ(to_string(*C.intersect(L1.iterator(), C.none())), "false");
+  EXPECT_EQ(llvm::to_string(*C.intersect(L1.iterator(), C.all())), "[1]");
+  EXPECT_EQ(llvm::to_string(*C.intersect(L1.iterator(), C.none())), "false");
   // Not optimized to avoid breaking boosts.
-  EXPECT_EQ(to_string(*C.unionOf(L1.iterator(), C.all())), "(| [1] true)");
-  EXPECT_EQ(to_string(*C.unionOf(L1.iterator(), C.none())), "[1]");
+  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]");
 
   // and/or nested inside and/or are flattened
-  EXPECT_EQ(to_string(*C.intersect(L1.iterator(),
-                                   C.intersect(L1.iterator(), L1.iterator()))),
+  EXPECT_EQ(llvm::to_string(*C.intersect(
+                L1.iterator(), C.intersect(L1.iterator(), L1.iterator()))),
             "(& [1] [1] [1])");
-  EXPECT_EQ(to_string(*C.unionOf(L1.iterator(),
-                                 C.unionOf(L2.iterator(), L3.iterator()))),
+  EXPECT_EQ(llvm::to_string(*C.unionOf(
+                L1.iterator(), C.unionOf(L2.iterator(), L3.iterator()))),
             "(| [1] [2] [3])");
 
   // optimizations combine over multiple levels
-  EXPECT_EQ(to_string(*C.intersect(C.intersect(L1.iterator(), C.intersect()),
-                                   C.unionOf(C.all()))),
+  EXPECT_EQ(llvm::to_string(*C.intersect(
+                C.intersect(L1.iterator(), C.intersect()), C.unionOf(C.all()))),
             "[1]");
 }
 
@@ -657,7 +657,7 @@ TEST(DexTest, ProximityPathsBoosting) {
 }
 
 TEST(DexTests, Refs) {
-  DenseMap<SymbolID, std::vector<Ref>> Refs;
+  llvm::DenseMap<SymbolID, std::vector<Ref>> Refs;
   auto AddRef = [&](const Symbol &Sym, const char *Filename, RefKind Kind) {
     auto &SymbolRefs = Refs[Sym.ID];
     SymbolRefs.emplace_back();

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp Mon Jan  7 07:45:19 2019
@@ -13,29 +13,28 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
 
 struct IncrementalTestStep {
-  StringRef Src;
-  StringRef Contents;
+  llvm::StringRef Src;
+  llvm::StringRef Contents;
 };
 
-int rangeLength(StringRef Code, const Range &Rng) {
-  Expected<size_t> Start = positionToOffset(Code, Rng.start);
-  Expected<size_t> End = positionToOffset(Code, Rng.end);
+int rangeLength(llvm::StringRef Code, const Range &Rng) {
+  llvm::Expected<size_t> Start = positionToOffset(Code, Rng.start);
+  llvm::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(ArrayRef<IncrementalTestStep> Steps) {
+void stepByStep(llvm::ArrayRef<IncrementalTestStep> Steps) {
   DraftStore DS;
   Annotations InitialSrc(Steps.front().Src);
-  constexpr StringLiteral Path("/hello.cpp");
+  constexpr llvm::StringLiteral Path("/hello.cpp");
 
   // Set the initial content.
   DS.addDraft(Path, InitialSrc.code());
@@ -43,14 +42,14 @@ void stepByStep(ArrayRef<IncrementalTest
   for (size_t i = 1; i < Steps.size(); i++) {
     Annotations SrcBefore(Steps[i - 1].Src);
     Annotations SrcAfter(Steps[i].Src);
-    StringRef Contents = Steps[i - 1].Contents;
+    llvm::StringRef Contents = Steps[i - 1].Contents;
     TextDocumentContentChangeEvent Event{
         SrcBefore.range(),
         rangeLength(SrcBefore.code(), SrcBefore.range()),
         Contents.str(),
     };
 
-    Expected<std::string> Result = DS.updateDraft(Path, {Event});
+    llvm::Expected<std::string> Result = DS.updateDraft(Path, {Event});
     ASSERT_TRUE(!!Result);
     EXPECT_EQ(*Result, SrcAfter.code());
     EXPECT_EQ(*DS.getDraft(Path), SrcAfter.code());
@@ -58,16 +57,16 @@ void stepByStep(ArrayRef<IncrementalTest
 }
 
 /// Send all the changes at once to updateDraft, check only the final result.
-void allAtOnce(ArrayRef<IncrementalTestStep> Steps) {
+void allAtOnce(llvm::ArrayRef<IncrementalTestStep> Steps) {
   DraftStore DS;
   Annotations InitialSrc(Steps.front().Src);
   Annotations FinalSrc(Steps.back().Src);
-  constexpr StringLiteral Path("/hello.cpp");
+  constexpr llvm::StringLiteral Path("/hello.cpp");
   std::vector<TextDocumentContentChangeEvent> Changes;
 
   for (size_t i = 0; i < Steps.size() - 1; i++) {
     Annotations Src(Steps[i].Src);
-    StringRef Contents = Steps[i].Contents;
+    llvm::StringRef Contents = Steps[i].Contents;
 
     Changes.push_back({
         Src.range(),
@@ -79,9 +78,9 @@ void allAtOnce(ArrayRef<IncrementalTestS
   // Set the initial content.
   DS.addDraft(Path, InitialSrc.code());
 
-  Expected<std::string> Result = DS.updateDraft(Path, Changes);
+  llvm::Expected<std::string> Result = DS.updateDraft(Path, Changes);
 
-  ASSERT_TRUE(!!Result) << toString(Result.takeError());
+  ASSERT_TRUE(!!Result) << llvm::toString(Result.takeError());
   EXPECT_EQ(*Result, FinalSrc.code());
   EXPECT_EQ(*DS.getDraft(Path), FinalSrc.code());
 }

Modified: clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp Mon Jan  7 07:45:19 2019
@@ -17,8 +17,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
-
 namespace clang {
 namespace clangd {
 namespace {
@@ -30,21 +28,21 @@ using ::testing::UnorderedElementsAreArr
 
 class ExpectedTypeConversionTest : public ::testing::Test {
 protected:
-  void build(StringRef Code) {
+  void build(llvm::StringRef Code) {
     assert(!AST && "AST built twice");
     AST = TestTU::withCode(Code).build();
   }
 
-  const ValueDecl *decl(StringRef Name) {
+  const ValueDecl *decl(llvm::StringRef Name) {
     return &cast<ValueDecl>(findDecl(*AST, Name));
   }
 
-  QualType typeOf(StringRef Name) {
+  QualType typeOf(llvm::StringRef Name) {
     return decl(Name)->getType().getCanonicalType();
   }
 
   /// An overload for convenience.
-  Optional<OpaqueType> fromCompletionResult(const ValueDecl *D) {
+  llvm::Optional<OpaqueType> fromCompletionResult(const ValueDecl *D) {
     return OpaqueType::fromCompletionResult(
         ASTCtx(), CodeCompletionResult(D, CCP_Declaration));
   }
@@ -54,7 +52,7 @@ protected:
   using EquivClass = std::set<std::string>;
 
   Matcher<std::map<std::string, EquivClass>>
-  ClassesAre(ArrayRef<EquivClass> Classes) {
+  ClassesAre(llvm::ArrayRef<EquivClass> Classes) {
     using MapEntry = std::map<std::string, EquivClass>::value_type;
 
     std::vector<Matcher<MapEntry>> Elements;
@@ -67,9 +65,9 @@ protected:
   // Groups \p Decls into equivalence classes based on the result of
   // 'OpaqueType::fromCompletionResult'.
   std::map<std::string, EquivClass>
-  buildEquivClasses(ArrayRef<StringRef> DeclNames) {
+  buildEquivClasses(llvm::ArrayRef<llvm::StringRef> DeclNames) {
     std::map<std::string, EquivClass> Classes;
-    for (StringRef Name : DeclNames) {
+    for (llvm::StringRef Name : DeclNames) {
       auto Type = OpaqueType::fromType(ASTCtx(), typeOf(Name));
       Classes[Type->raw()].insert(Name);
     }
@@ -80,7 +78,7 @@ protected:
 
 private:
   // Set after calling build().
-  Optional<ParsedAST> AST;
+  llvm::Optional<ParsedAST> AST;
 };
 
 TEST_F(ExpectedTypeConversionTest, BasicTypes) {

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/FSTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/FSTests.cpp Mon Jan  7 07:45:19 2019
@@ -12,13 +12,12 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
 
 TEST(FSTests, PreambleStatusCache) {
-  StringMap<std::string> Files;
+  llvm::StringMap<std::string> Files;
   Files["x"] = "";
   Files["y"] = "";
   Files["main"] = "";
@@ -36,9 +35,10 @@ TEST(FSTests, PreambleStatusCache) {
   // Main file is not cached.
   EXPECT_FALSE(StatCache.lookup(testPath("main")).hasValue());
 
-  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);
+  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);
   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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp Mon Jan  7 07:45:19 2019
@@ -31,7 +31,6 @@ using testing::ElementsAre;
 using testing::IsEmpty;
 using testing::Pair;
 using testing::UnorderedElementsAre;
-using namespace llvm;
 
 MATCHER_P(RefRange, Range, "") {
   return std::make_tuple(arg.Location.Start.line(), arg.Location.Start.column(),
@@ -39,11 +38,13 @@ MATCHER_P(RefRange, Range, "") {
          std::make_tuple(Range.start.line, Range.start.character,
                          Range.end.line, Range.end.character);
 }
-MATCHER_P(FileURI, F, "") { return StringRef(arg.Location.FileURI) == F; }
+MATCHER_P(FileURI, F, "") { return llvm::StringRef(arg.Location.FileURI) == F; }
 MATCHER_P(DeclURI, U, "") {
-  return StringRef(arg.CanonicalDeclaration.FileURI) == U;
+  return llvm::StringRef(arg.CanonicalDeclaration.FileURI) == U;
+}
+MATCHER_P(DefURI, U, "") {
+  return llvm::StringRef(arg.Definition.FileURI) == U;
 }
-MATCHER_P(DefURI, U, "") { return StringRef(arg.Definition.FileURI) == U; }
 MATCHER_P(QName, N, "") { return (arg.Scope + arg.Name).str() == N; }
 
 namespace clang {
@@ -54,7 +55,7 @@ RefsAre(std::vector<testing::Matcher<Ref
   return ElementsAre(testing::Pair(_, UnorderedElementsAreArray(Matchers)));
 }
 
-Symbol symbol(StringRef ID) {
+Symbol symbol(llvm::StringRef ID) {
   Symbol Sym;
   Sym.ID = SymbolID(ID);
   Sym.Name = ID;
@@ -103,7 +104,7 @@ TEST(FileSymbolsTest, MergeOverlap) {
   auto OneSymboSlab = [](Symbol Sym) {
     SymbolSlab::Builder S;
     S.insert(Sym);
-    return make_unique<SymbolSlab>(std::move(S).build());
+    return llvm::make_unique<SymbolSlab>(std::move(S).build());
   };
   auto X1 = symbol("x");
   X1.CanonicalDeclaration.FileURI = "file:///x1";
@@ -141,7 +142,7 @@ TEST(FileSymbolsTest, SnapshotAliveAfter
 }
 
 // Adds Basename.cpp, which includes Basename.h, which contains Code.
-void update(FileIndex &M, StringRef Basename, StringRef Code) {
+void update(FileIndex &M, llvm::StringRef Basename, llvm::StringRef Code) {
   TestTU File;
   File.Filename = (Basename + ".cpp").str();
   File.HeaderFilename = (Basename + ".h").str();
@@ -246,7 +247,7 @@ TEST(FileIndexTest, RebuildWithPreamble)
   PI.CompileCommand.Filename = FooCpp;
   PI.CompileCommand.CommandLine = {"clang", "-xc++", FooCpp};
 
-  StringMap<std::string> Files;
+  llvm::StringMap<std::string> Files;
   Files[FooCpp] = "";
   Files[FooH] = R"cpp(
     namespace ns_in_header {
@@ -362,7 +363,7 @@ TEST(FileIndexTest, ReferencesInMainFile
   // Build AST for main file with preamble.
   auto AST =
       ParsedAST::build(createInvocationFromCommandLine(Cmd), PreambleData,
-                       MemoryBuffer::getMemBufferCopy(Main.code()),
+                       llvm::MemoryBuffer::getMemBufferCopy(Main.code()),
                        std::make_shared<PCHContainerOperations>(), PI.FS);
   ASSERT_TRUE(AST);
   FileIndex Index;

Modified: clang-tools-extra/trunk/unittests/clangd/FindSymbolsTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/FindSymbolsTests.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/FindSymbolsTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/FindSymbolsTests.cpp Mon Jan  7 07:45:19 2019
@@ -14,8 +14,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
-
 namespace clang {
 namespace clangd {
 
@@ -73,14 +71,14 @@ protected:
   ClangdServer Server;
   int Limit = 0;
 
-  std::vector<SymbolInformation> getSymbols(StringRef Query) {
+  std::vector<SymbolInformation> getSymbols(llvm::StringRef Query) {
     EXPECT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for preamble";
     auto SymbolInfos = runWorkspaceSymbols(Server, Query, Limit);
     EXPECT_TRUE(bool(SymbolInfos)) << "workspaceSymbols returned an error";
     return *SymbolInfos;
   }
 
-  void addFile(StringRef FileName, StringRef Contents) {
+  void addFile(llvm::StringRef FileName, llvm::StringRef Contents) {
     auto Path = testPath(FileName);
     FSProvider.Files[Path] = Contents;
     Server.addDocument(Path, Contents);
@@ -318,7 +316,7 @@ protected:
     return *SymbolInfos;
   }
 
-  void addFile(StringRef FilePath, StringRef Contents) {
+  void addFile(llvm::StringRef FilePath, llvm::StringRef Contents) {
     FSProvider.Files[FilePath] = Contents;
     Server.addDocument(FilePath, Contents);
   }

Modified: clang-tools-extra/trunk/unittests/clangd/FunctionTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/FunctionTests.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/FunctionTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/FunctionTests.cpp Mon Jan  7 07:45:19 2019
@@ -11,7 +11,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp Mon Jan  7 07:45:19 2019
@@ -13,7 +13,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -21,17 +20,18 @@ using testing::Not;
 
 struct ExpectedMatch {
   // Annotations are optional, and will not be asserted if absent.
-  ExpectedMatch(StringRef Match) : Word(Match), Annotated(Match) {
+  ExpectedMatch(llvm::StringRef Match) : Word(Match), Annotated(Match) {
     for (char C : "[]")
       Word.erase(std::remove(Word.begin(), Word.end(), C), Word.end());
     if (Word.size() == Annotated->size())
-      Annotated = None;
+      Annotated = llvm::None;
   }
-  bool accepts(StringRef ActualAnnotated) const {
+  bool accepts(llvm::StringRef ActualAnnotated) const {
     return !Annotated || ActualAnnotated == *Annotated;
   }
 
-  friend raw_ostream &operator<<(raw_ostream &OS, const ExpectedMatch &M) {
+  friend llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+                                       const ExpectedMatch &M) {
     OS << "'" << M.Word;
     if (M.Annotated)
       OS << "' as " << *M.Annotated;
@@ -41,26 +41,27 @@ struct ExpectedMatch {
   std::string Word;
 
 private:
-  Optional<StringRef> Annotated;
+  llvm::Optional<llvm::StringRef> Annotated;
 };
 
-struct MatchesMatcher : public testing::MatcherInterface<StringRef> {
+struct MatchesMatcher : public testing::MatcherInterface<llvm::StringRef> {
   ExpectedMatch Candidate;
-  Optional<float> Score;
-  MatchesMatcher(ExpectedMatch Candidate, Optional<float> Score)
+  llvm::Optional<float> Score;
+  MatchesMatcher(ExpectedMatch Candidate, llvm::Optional<float> Score)
       : Candidate(std::move(Candidate)), Score(Score) {}
 
   void DescribeTo(::std::ostream *OS) const override {
-    raw_os_ostream(*OS) << "Matches " << Candidate;
+    llvm::raw_os_ostream(*OS) << "Matches " << Candidate;
     if (Score)
       *OS << " with score " << *Score;
   }
 
-  bool MatchAndExplain(StringRef Pattern,
+  bool MatchAndExplain(llvm::StringRef Pattern,
                        testing::MatchResultListener *L) const override {
-    std::unique_ptr<raw_ostream> OS(
-        L->stream() ? (raw_ostream *)(new raw_os_ostream(*L->stream()))
-                    : new raw_null_ostream());
+    std::unique_ptr<llvm::raw_ostream> OS(
+        L->stream()
+            ? (llvm::raw_ostream *)(new llvm::raw_os_ostream(*L->stream()))
+            : new llvm::raw_null_ostream());
     FuzzyMatcher Matcher(Pattern);
     auto Result = Matcher.match(Candidate.Word);
     auto AnnotatedMatch = Matcher.dumpLast(*OS << "\n");
@@ -71,8 +72,9 @@ struct MatchesMatcher : public testing::
 
 // Accepts patterns that match a given word, optionally requiring a score.
 // Dumps the debug tables on match failure.
-testing::Matcher<StringRef> matches(StringRef M, Optional<float> Score = {}) {
-  return testing::MakeMatcher<StringRef>(new MatchesMatcher(M, Score));
+testing::Matcher<llvm::StringRef> matches(llvm::StringRef M,
+                                          llvm::Optional<float> Score = {}) {
+  return testing::MakeMatcher<llvm::StringRef>(new MatchesMatcher(M, Score));
 }
 
 TEST(FuzzyMatch, Matches) {
@@ -178,27 +180,28 @@ TEST(FuzzyMatch, Matches) {
   EXPECT_THAT("std", Not(matches("pthread_condattr_setpshared")));
 }
 
-struct RankMatcher : public testing::MatcherInterface<StringRef> {
+struct RankMatcher : public testing::MatcherInterface<llvm::StringRef> {
   std::vector<ExpectedMatch> RankedStrings;
   RankMatcher(std::initializer_list<ExpectedMatch> RankedStrings)
       : RankedStrings(RankedStrings) {}
 
   void DescribeTo(::std::ostream *OS) const override {
-    raw_os_ostream O(*OS);
+    llvm::raw_os_ostream O(*OS);
     O << "Ranks strings in order: [";
     for (const auto &Str : RankedStrings)
       O << "\n\t" << Str;
     O << "\n]";
   }
 
-  bool MatchAndExplain(StringRef Pattern,
+  bool MatchAndExplain(llvm::StringRef Pattern,
                        testing::MatchResultListener *L) const override {
-    std::unique_ptr<raw_ostream> OS(
-        L->stream() ? (raw_ostream *)(new raw_os_ostream(*L->stream()))
-                    : new raw_null_ostream());
+    std::unique_ptr<llvm::raw_ostream> OS(
+        L->stream()
+            ? (llvm::raw_ostream *)(new llvm::raw_os_ostream(*L->stream()))
+            : new llvm::raw_null_ostream());
     FuzzyMatcher Matcher(Pattern);
     const ExpectedMatch *LastMatch;
-    Optional<float> LastScore;
+    llvm::Optional<float> LastScore;
     bool Ok = true;
     for (const auto &Str : RankedStrings) {
       auto Score = Matcher.match(Str.Word);
@@ -208,7 +211,7 @@ struct RankMatcher : public testing::Mat
         Ok = false;
       } else {
         std::string Buf;
-        raw_string_ostream Info(Buf);
+        llvm::raw_string_ostream Info(Buf);
         auto AnnotatedMatch = Matcher.dumpLast(Info);
 
         if (!Str.accepts(AnnotatedMatch)) {
@@ -233,8 +236,9 @@ struct RankMatcher : public testing::Mat
 
 // Accepts patterns that match all the strings and rank them in the given order.
 // Dumps the debug tables on match failure.
-template <typename... T> testing::Matcher<StringRef> ranks(T... RankedStrings) {
-  return testing::MakeMatcher<StringRef>(
+template <typename... T>
+testing::Matcher<llvm::StringRef> ranks(T... RankedStrings) {
+  return testing::MakeMatcher<llvm::StringRef>(
       new RankMatcher{ExpectedMatch(RankedStrings)...});
 }
 
@@ -275,7 +279,7 @@ TEST(FuzzyMatch, Scoring) {
 
 // Returns pretty-printed segmentation of Text.
 // e.g. std::basic_string --> +--  +---- +-----
-std::string segment(StringRef Text) {
+std::string segment(llvm::StringRef Text) {
   std::vector<CharRole> Roles(Text.size());
   calculateRoles(Text, Roles);
   std::string Printed;
@@ -285,7 +289,7 @@ std::string segment(StringRef Text) {
 }
 
 // this is a no-op hack so clang-format will vertically align our testcases.
-StringRef returns(StringRef Text) { return Text; }
+llvm::StringRef returns(llvm::StringRef Text) { return Text; }
 
 TEST(FuzzyMatch, Segmentation) {
   EXPECT_THAT(segment("std::basic_string"), //

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/GlobalCompilationDatabaseTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/GlobalCompilationDatabaseTests.cpp Mon Jan  7 07:45:19 2019
@@ -14,7 +14,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -36,15 +35,16 @@ TEST(GlobalCompilationDatabaseTest, Fall
                           testPath("foo/bar.h")));
 }
 
-static tooling::CompileCommand cmd(StringRef File, StringRef Arg) {
+static tooling::CompileCommand cmd(llvm::StringRef File, llvm::StringRef Arg) {
   return tooling::CompileCommand(testRoot(), File, {"clang", Arg, File}, "");
 }
 
 class OverlayCDBTest : public ::testing::Test {
   class BaseCDB : public GlobalCompilationDatabase {
   public:
-    Optional<tooling::CompileCommand>
-    getCompileCommand(StringRef File, ProjectInfo *Project) const override {
+    llvm::Optional<tooling::CompileCommand>
+    getCompileCommand(llvm::StringRef File,
+                      ProjectInfo *Project) const override {
       if (File == testPath("foo.cc")) {
         if (Project)
           Project->SourceRoot = testRoot();
@@ -53,7 +53,8 @@ class OverlayCDBTest : public ::testing:
       return None;
     }
 
-    tooling::CompileCommand getFallbackCommand(StringRef File) const override {
+    tooling::CompileCommand
+    getFallbackCommand(llvm::StringRef File) const override {
       return cmd(File, "-DA=2");
     }
   };

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/HeadersTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/HeadersTests.cpp Mon Jan  7 07:45:19 2019
@@ -19,7 +19,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -53,7 +52,7 @@ private:
     CI->getDiagnosticOpts().IgnoreWarnings = true;
     auto Clang = prepareCompilerInstance(
         std::move(CI), /*Preamble=*/nullptr,
-        MemoryBuffer::getMemBuffer(FS.Files[MainFile], MainFile),
+        llvm::MemoryBuffer::getMemBuffer(FS.Files[MainFile], MainFile),
         std::make_shared<PCHContainerOperations>(), VFS, IgnoreDiags);
 
     EXPECT_FALSE(Clang->getFrontendOpts().Inputs.empty());
@@ -85,9 +84,9 @@ protected:
 
     if (Preferred.empty())
       Preferred = Original;
-    auto ToHeaderFile = [](StringRef Header) {
+    auto ToHeaderFile = [](llvm::StringRef Header) {
       return HeaderFile{Header,
-                        /*Verbatim=*/!sys::path::is_absolute(Header)};
+                        /*Verbatim=*/!llvm::sys::path::is_absolute(Header)};
     };
 
     IncludeInserter Inserter(MainFile, /*Code=*/"", format::getLLVMStyle(),
@@ -104,7 +103,7 @@ protected:
     return Path;
   }
 
-  Optional<TextEdit> insert(StringRef VerbatimHeader) {
+  llvm::Optional<TextEdit> insert(llvm::StringRef VerbatimHeader) {
     auto Clang = setupClang();
     PreprocessOnlyAction Action;
     EXPECT_TRUE(
@@ -122,7 +121,7 @@ protected:
   MockCompilationDatabase CDB;
   std::string MainFile = testPath("main.cpp");
   std::string Subdir = testPath("sub");
-  std::string SearchDirArg = (Twine("-I") + Subdir).str();
+  std::string SearchDirArg = (llvm::Twine("-I") + Subdir).str();
   IgnoringDiagConsumer IgnoreDiags;
 };
 

Modified: clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp Mon Jan  7 07:45:19 2019
@@ -68,7 +68,7 @@ public:
   runIndexingAction(llvm::StringRef MainFilePath,
                     const std::vector<std::string> &ExtraArgs = {}) {
     IndexFileIn IndexFile;
-    IntrusiveRefCntPtr<FileManager> Files(
+    llvm::IntrusiveRefCntPtr<FileManager> Files(
         new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
     auto Action = createStaticIndexingAction(
@@ -101,7 +101,7 @@ public:
 
 protected:
   std::vector<std::string> FilePaths;
-  IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem;
+  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem;
 };
 
 TEST_F(IndexActionTest, CollectIncludeGraph) {

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp Mon Jan  7 07:45:19 2019
@@ -24,7 +24,6 @@ using testing::Pair;
 using testing::Pointee;
 using testing::UnorderedElementsAre;
 
-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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/JSONTransportTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/JSONTransportTests.cpp Mon Jan  7 07:45:19 2019
@@ -12,7 +12,6 @@
 #include "gtest/gtest.h"
 #include <stdio.h>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -25,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;
-  raw_string_ostream Out, Mirror;
+  llvm::raw_string_ostream Out, Mirror;
   std::unique_ptr<FILE, int (*)(FILE *)> In;
 
 protected:
@@ -52,40 +51,43 @@ protected:
 class Echo : public Transport::MessageHandler {
   Transport &Target;
   std::string LogBuf;
-  raw_string_ostream Log;
+  llvm::raw_string_ostream Log;
 
 public:
   Echo(Transport &Target) : Target(Target), Log(LogBuf) {}
 
   std::string log() { return Log.str(); }
 
-  bool onNotify(StringRef Method, json::Value Params) override {
+  bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
     Log << "Notification " << Method << ": " << Params << "\n";
     if (Method == "call")
       Target.call("echo call", std::move(Params), 42);
     return Method != "exit";
   }
 
-  bool onCall(StringRef Method, json::Value Params, json::Value ID) override {
+  bool onCall(llvm::StringRef Method, llvm::json::Value Params,
+              llvm::json::Value ID) override {
     Log << "Call " << Method << "(" << ID << "): " << Params << "\n";
     if (Method == "err")
-      Target.reply(ID, make_error<LSPError>("trouble at mill", ErrorCode(88)));
+      Target.reply(
+          ID, llvm::make_error<LSPError>("trouble at mill", ErrorCode(88)));
     else
       Target.reply(ID, std::move(Params));
     return true;
   }
 
-  bool onReply(json::Value ID, Expected<json::Value> Params) override {
+  bool onReply(llvm::json::Value ID,
+               llvm::Expected<llvm::json::Value> Params) override {
     if (Params)
       Log << "Reply(" << ID << "): " << *Params << "\n";
     else
-      Log << "Reply(" << ID << "): error = " << toString(Params.takeError())
-          << "\n";
+      Log << "Reply(" << ID
+          << "): error = " << llvm::toString(Params.takeError()) << "\n";
     return true;
   }
 };
 
-std::string trim(StringRef S) { return S.trim().str(); }
+std::string trim(llvm::StringRef S) { return S.trim().str(); }
 
 // Runs an Echo session using the standard JSON-RPC format we use in production.
 TEST_F(JSONTransportTest, StandardDense) {

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp Mon Jan  7 07:45:19 2019
@@ -30,7 +30,6 @@
 #include "gtest/gtest.h"
 #include <vector>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -253,7 +252,7 @@ TEST(QualityTests, SymbolRelevanceSignal
 
   SymbolRelevanceSignals IndexProximate;
   IndexProximate.SymbolURI = "unittest:/foo/bar.h";
-  StringMap<SourceParams> ProxSources;
+  llvm::StringMap<SourceParams> ProxSources;
   ProxSources.try_emplace(testPath("foo/baz.h"));
   URIDistance Distance(ProxSources);
   IndexProximate.FileProximityMatch = &Distance;

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/RIFFTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/RIFFTests.cpp Mon Jan  7 07:45:19 2019
@@ -11,7 +11,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -23,12 +22,12 @@ TEST(RIFFTest, File) {
                       {riff::fourCC("even"), "abcd"},
                       {riff::fourCC("oddd"), "abcde"},
                   }};
-  StringRef Serialized = StringRef("RIFF\x1e\0\0\0test"
-                                   "even\x04\0\0\0abcd"
-                                   "oddd\x05\0\0\0abcde\0",
-                                   38);
+  llvm::StringRef Serialized = llvm::StringRef("RIFF\x1e\0\0\0test"
+                                               "even\x04\0\0\0abcd"
+                                               "oddd\x05\0\0\0abcde\0",
+                                               38);
 
-  EXPECT_EQ(to_string(File), Serialized);
+  EXPECT_EQ(llvm::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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp Mon Jan  7 07:45:19 2019
@@ -20,7 +20,6 @@ using testing::Pair;
 using testing::UnorderedElementsAre;
 using testing::UnorderedElementsAreArray;
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -158,7 +157,7 @@ TEST(SerializationTest, BinaryConversion
   // Write to binary format, and parse again.
   IndexFileOut Out(*In);
   Out.Format = IndexFileFormat::RIFF;
-  std::string Serialized = to_string(Out);
+  std::string Serialized = llvm::to_string(Out);
 
   auto In2 = readIndexFile(Serialized);
   ASSERT_TRUE(bool(In2)) << In.takeError();
@@ -191,7 +190,7 @@ TEST(SerializationTest, SrcsTest) {
   Out.Format = IndexFileFormat::RIFF;
   Out.Sources = &Sources;
   {
-    std::string Serialized = to_string(Out);
+    std::string Serialized = llvm::to_string(Out);
 
     auto In = readIndexFile(Serialized);
     ASSERT_TRUE(bool(In)) << 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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp Mon Jan  7 07:45:19 2019
@@ -13,7 +13,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -54,63 +53,63 @@ TEST(SourceCodeTests, lspLength) {
 
 TEST(SourceCodeTests, PositionToOffset) {
   // line out of bounds
-  EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), Failed());
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
   // first line
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, -1)),
-                       Failed()); // out of range
+                       llvm::Failed()); // out of range
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 0)),
-                       HasValue(0)); // first character
+                       llvm::HasValue(0)); // first character
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 3)),
-                       HasValue(3)); // middle character
+                       llvm::HasValue(3)); // middle character
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 6)),
-                       HasValue(6)); // last character
+                       llvm::HasValue(6)); // last character
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7)),
-                       HasValue(7)); // the newline itself
+                       llvm::HasValue(7)); // the newline itself
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7), false),
-                       HasValue(7));
+                       llvm::HasValue(7));
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8)),
-                       HasValue(7)); // out of range
+                       llvm::HasValue(7)); // out of range
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8), false),
-                       Failed()); // out of range
+                       llvm::Failed()); // out of range
   // middle line
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, -1)),
-                       Failed()); // out of range
+                       llvm::Failed()); // out of range
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 0)),
-                       HasValue(8)); // first character
+                       llvm::HasValue(8)); // first character
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3)),
-                       HasValue(11)); // middle character
+                       llvm::HasValue(11)); // middle character
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3), false),
-                       HasValue(11));
+                       llvm::HasValue(11));
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 6)),
-                       HasValue(16)); // last character
+                       llvm::HasValue(16)); // last character
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 7)),
-                       HasValue(17)); // the newline itself
+                       llvm::HasValue(17)); // the newline itself
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8)),
-                       HasValue(17)); // out of range
+                       llvm::HasValue(17)); // out of range
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8), false),
-                       Failed()); // out of range
+                       llvm::Failed()); // out of range
   // last line
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, -1)),
-                       Failed()); // out of range
+                       llvm::Failed()); // out of range
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 0)),
-                       HasValue(18)); // first character
+                       llvm::HasValue(18)); // first character
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 3)),
-                       HasValue(21)); // middle character
+                       llvm::HasValue(21)); // middle character
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 5), false),
-                       Failed()); // middle of surrogate pair
+                       llvm::Failed()); // middle of surrogate pair
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 5)),
-                       HasValue(26)); // middle of surrogate pair
+                       llvm::HasValue(26)); // middle of surrogate pair
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 6), false),
-                       HasValue(26)); // end of surrogate pair
+                       llvm::HasValue(26)); // end of surrogate pair
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 8)),
-                       HasValue(28)); // last character
+                       llvm::HasValue(28)); // last character
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 9)),
-                       HasValue(29)); // EOF
+                       llvm::HasValue(29)); // EOF
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 10), false),
-                       Failed()); // out of range
+                       llvm::Failed()); // out of range
   // line out of bounds
-  EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), Failed());
-  EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), Failed());
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), llvm::Failed());
 }
 
 TEST(SourceCodeTests, OffsetToPosition) {

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp Mon Jan  7 07:45:19 2019
@@ -27,7 +27,6 @@
 #include <memory>
 #include <string>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -103,7 +102,7 @@ HaveRanges(const std::vector<Range> Rang
 
 class ShouldCollectSymbolTest : public ::testing::Test {
 public:
-  void build(StringRef HeaderCode, StringRef Code = "") {
+  void build(llvm::StringRef HeaderCode, llvm::StringRef Code = "") {
     File.HeaderFilename = HeaderName;
     File.Filename = FileName;
     File.HeaderCode = HeaderCode;
@@ -112,7 +111,7 @@ public:
   }
 
   // build() must have been called.
-  bool shouldCollect(StringRef Name, bool Qualified = true) {
+  bool shouldCollect(llvm::StringRef Name, bool Qualified = true) {
     assert(AST.hasValue());
     return SymbolCollector::shouldCollectSymbol(
         Qualified ? findDecl(*AST, Name) : findUnqualifiedDecl(*AST, Name),
@@ -123,7 +122,7 @@ protected:
   std::string HeaderName = "f.h";
   std::string FileName = "f.cpp";
   TestTU File;
-  Optional<ParsedAST> AST; // Initialized after build.
+  llvm::Optional<ParsedAST> AST; // Initialized after build.
 };
 
 TEST_F(ShouldCollectSymbolTest, ShouldCollectSymbol) {
@@ -197,7 +196,7 @@ public:
             PragmaHandler(PragmaHandler) {}
 
       std::unique_ptr<ASTConsumer>
-      CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
+      CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
         if (PragmaHandler)
           CI.getPreprocessor().addCommentHandler(PragmaHandler);
         return WrapperFrontendAction::CreateASTConsumer(CI, InFile);
@@ -224,16 +223,16 @@ public:
 class SymbolCollectorTest : public ::testing::Test {
 public:
   SymbolCollectorTest()
-      : InMemoryFileSystem(new vfs::InMemoryFileSystem),
+      : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem),
         TestHeaderName(testPath("symbol.h")),
         TestFileName(testPath("symbol.cc")) {
     TestHeaderURI = URI::create(TestHeaderName).toString();
     TestFileURI = URI::create(TestFileName).toString();
   }
 
-  bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode,
+  bool runSymbolCollector(llvm::StringRef HeaderCode, llvm::StringRef MainCode,
                           const std::vector<std::string> &ExtraArgs = {}) {
-    IntrusiveRefCntPtr<FileManager> Files(
+    llvm::IntrusiveRefCntPtr<FileManager> Files(
         new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
     auto Factory = llvm::make_unique<SymbolIndexActionFactory>(
@@ -252,9 +251,9 @@ public:
         std::make_shared<PCHContainerOperations>());
 
     InMemoryFileSystem->addFile(TestHeaderName, 0,
-                                MemoryBuffer::getMemBuffer(HeaderCode));
+                                llvm::MemoryBuffer::getMemBuffer(HeaderCode));
     InMemoryFileSystem->addFile(TestFileName, 0,
-                                MemoryBuffer::getMemBuffer(MainCode));
+                                llvm::MemoryBuffer::getMemBuffer(MainCode));
     Invocation.run();
     Symbols = Factory->Collector->takeSymbols();
     Refs = Factory->Collector->takeRefs();
@@ -262,7 +261,7 @@ public:
   }
 
 protected:
-  IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem;
+  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem;
   std::string TestHeaderName;
   std::string TestHeaderURI;
   std::string TestFileName;
@@ -829,7 +828,7 @@ TEST_F(SymbolCollectorTest, SkipIncFileW
   auto IncFile = testPath("test.inc");
   auto IncURI = URI::create(IncFile).toString();
   InMemoryFileSystem->addFile(IncFile, 0,
-                              MemoryBuffer::getMemBuffer("class X {};"));
+                              llvm::MemoryBuffer::getMemBuffer("class X {};"));
   runSymbolCollector("#include \"test.inc\"\nclass Y {};", /*Main=*/"",
                      /*ExtraArgs=*/{"-I", testRoot()});
   EXPECT_THAT(Symbols,
@@ -848,7 +847,7 @@ TEST_F(SymbolCollectorTest, MainFileIsHe
   auto IncFile = testPath("test.inc");
   auto IncURI = URI::create(IncFile).toString();
   InMemoryFileSystem->addFile(IncFile, 0,
-                              MemoryBuffer::getMemBuffer("class X {};"));
+                              llvm::MemoryBuffer::getMemBuffer("class X {};"));
   runSymbolCollector("", /*Main=*/"#include \"test.inc\"",
                      /*ExtraArgs=*/{"-I", testRoot()});
   EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(QName("X"), DeclURI(IncURI),
@@ -864,7 +863,7 @@ TEST_F(SymbolCollectorTest, MainFileIsHe
   auto IncFile = testPath("test.inc");
   auto IncURI = URI::create(IncFile).toString();
   InMemoryFileSystem->addFile(IncFile, 0,
-                              MemoryBuffer::getMemBuffer("class X {};"));
+                              llvm::MemoryBuffer::getMemBuffer("class X {};"));
   runSymbolCollector("", /*Main=*/"#include \"test.inc\"",
                      /*ExtraArgs=*/{"-I", testRoot()});
   EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(QName("X"), DeclURI(IncURI),
@@ -878,7 +877,7 @@ TEST_F(SymbolCollectorTest, FallbackToIn
   auto IncFile = testPath("test.inc");
   auto IncURI = URI::create(IncFile).toString();
   InMemoryFileSystem->addFile(IncFile, 0,
-                              MemoryBuffer::getMemBuffer("class X {};"));
+                              llvm::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/SymbolInfoTests.cpp
URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/SymbolInfoTests.cpp?rev=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/SymbolInfoTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SymbolInfoTests.cpp Mon Jan  7 07:45:19 2019
@@ -21,7 +21,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/SyncAPI.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SyncAPI.cpp Mon Jan  7 07:45:19 2019
@@ -10,12 +10,11 @@
 #include "SyncAPI.h"
 #include "index/Index.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
-void runAddDocument(ClangdServer &Server, PathRef File, StringRef Contents,
-                    WantDiagnostics WantDiags) {
+void runAddDocument(ClangdServer &Server, PathRef File,
+                    llvm::StringRef Contents, WantDiagnostics WantDiags) {
   Server.addDocument(File, Contents, WantDiags);
   if (!Server.blockUntilIdleForTest())
     llvm_unreachable("not idle after addDocument");
@@ -27,7 +26,7 @@ namespace {
 ///    T Result;
 ///    someAsyncFunc(Param1, Param2, /*Callback=*/capture(Result));
 template <typename T> struct CaptureProxy {
-  CaptureProxy(Optional<T> &Target) : Target(&Target) {
+  CaptureProxy(llvm::Optional<T> &Target) : Target(&Target) {
     assert(!Target.hasValue());
   }
 
@@ -39,7 +38,7 @@ template <typename T> struct CaptureProx
   }
   CaptureProxy &operator=(CaptureProxy &&) = delete;
 
-  operator unique_function<void(T)>() && {
+  operator llvm::unique_function<void(T)>() && {
     assert(!Future.valid() && "conversion to callback called multiple times");
     Future = Promise.get_future();
     return Bind(
@@ -58,7 +57,7 @@ template <typename T> struct CaptureProx
   }
 
 private:
-  Optional<T> *Target;
+  llvm::Optional<T> *Target;
   // Using shared_ptr to workaround compilation errors with MSVC.
   // MSVC only allows default-construcitble and copyable objects as future<>
   // arguments.
@@ -66,68 +65,69 @@ private:
   std::future<std::shared_ptr<T>> Future;
 };
 
-template <typename T> CaptureProxy<T> capture(Optional<T> &Target) {
+template <typename T> CaptureProxy<T> capture(llvm::Optional<T> &Target) {
   return CaptureProxy<T>(Target);
 }
 } // namespace
 
-Expected<CodeCompleteResult> runCodeComplete(ClangdServer &Server, PathRef File,
-                                             Position Pos,
-                                             clangd::CodeCompleteOptions Opts) {
-  Optional<Expected<CodeCompleteResult>> Result;
+llvm::Expected<CodeCompleteResult>
+runCodeComplete(ClangdServer &Server, PathRef File, Position Pos,
+                clangd::CodeCompleteOptions Opts) {
+  llvm::Optional<llvm::Expected<CodeCompleteResult>> Result;
   Server.codeComplete(File, Pos, Opts, capture(Result));
   return std::move(*Result);
 }
 
-Expected<SignatureHelp> runSignatureHelp(ClangdServer &Server, PathRef File,
-                                         Position Pos) {
-  Optional<Expected<SignatureHelp>> Result;
+llvm::Expected<SignatureHelp> runSignatureHelp(ClangdServer &Server,
+                                               PathRef File, Position Pos) {
+  llvm::Optional<llvm::Expected<SignatureHelp>> Result;
   Server.signatureHelp(File, Pos, capture(Result));
   return std::move(*Result);
 }
 
-Expected<std::vector<Location>> runFindDefinitions(ClangdServer &Server,
-                                                   PathRef File, Position Pos) {
-  Optional<Expected<std::vector<Location>>> Result;
+llvm::Expected<std::vector<Location>>
+runFindDefinitions(ClangdServer &Server, PathRef File, Position Pos) {
+  llvm::Optional<llvm::Expected<std::vector<Location>>> Result;
   Server.findDefinitions(File, Pos, capture(Result));
   return std::move(*Result);
 }
 
-Expected<std::vector<DocumentHighlight>>
+llvm::Expected<std::vector<DocumentHighlight>>
 runFindDocumentHighlights(ClangdServer &Server, PathRef File, Position Pos) {
-  Optional<Expected<std::vector<DocumentHighlight>>> Result;
+  llvm::Optional<llvm::Expected<std::vector<DocumentHighlight>>> Result;
   Server.findDocumentHighlights(File, Pos, capture(Result));
   return std::move(*Result);
 }
 
-Expected<std::vector<tooling::Replacement>>
-runRename(ClangdServer &Server, PathRef File, Position Pos, StringRef NewName) {
-  Optional<Expected<std::vector<tooling::Replacement>>> Result;
+llvm::Expected<std::vector<tooling::Replacement>>
+runRename(ClangdServer &Server, PathRef File, Position Pos,
+          llvm::StringRef NewName) {
+  llvm::Optional<llvm::Expected<std::vector<tooling::Replacement>>> Result;
   Server.rename(File, Pos, NewName, capture(Result));
   return std::move(*Result);
 }
 
 std::string runDumpAST(ClangdServer &Server, PathRef File) {
-  Optional<std::string> Result;
+  llvm::Optional<std::string> Result;
   Server.dumpAST(File, capture(Result));
   return std::move(*Result);
 }
 
-Expected<std::vector<SymbolInformation>>
-runWorkspaceSymbols(ClangdServer &Server, StringRef Query, int Limit) {
-  Optional<Expected<std::vector<SymbolInformation>>> Result;
+llvm::Expected<std::vector<SymbolInformation>>
+runWorkspaceSymbols(ClangdServer &Server, llvm::StringRef Query, int Limit) {
+  llvm::Optional<llvm::Expected<std::vector<SymbolInformation>>> Result;
   Server.workspaceSymbols(Query, Limit, capture(Result));
   return std::move(*Result);
 }
 
-Expected<std::vector<DocumentSymbol>> runDocumentSymbols(ClangdServer &Server,
-                                                         PathRef File) {
-  Optional<Expected<std::vector<DocumentSymbol>>> Result;
+llvm::Expected<std::vector<DocumentSymbol>>
+runDocumentSymbols(ClangdServer &Server, PathRef File) {
+  llvm::Optional<llvm::Expected<std::vector<DocumentSymbol>>> Result;
   Server.documentSymbols(File, capture(Result));
   return std::move(*Result);
 }
 
-SymbolSlab runFuzzyFind(const SymbolIndex &Index, StringRef Query) {
+SymbolSlab runFuzzyFind(const SymbolIndex &Index, llvm::StringRef Query) {
   FuzzyFindRequest Req;
   Req.Query = Query;
   Req.AnyScope = true;

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp Mon Jan  7 07:45:19 2019
@@ -18,7 +18,6 @@
 #include <algorithm>
 #include <utility>
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -43,8 +42,8 @@ protected:
                        buildTestFS(Files, Timestamps), std::move(Contents)};
   }
 
-  void updateWithCallback(TUScheduler &S, PathRef File, StringRef Contents,
-                          WantDiagnostics WD,
+  void updateWithCallback(TUScheduler &S, PathRef File,
+                          llvm::StringRef Contents, WantDiagnostics WD,
                           llvm::unique_function<void()> CB) {
     WithContextValue Ctx(llvm::make_scope_exit(std::move(CB)));
     S.update(File, getInputs(File, Contents), WD);
@@ -93,8 +92,8 @@ protected:
                            std::move(CB));
   }
 
-  StringMap<std::string> Files;
-  StringMap<time_t> Timestamps;
+  llvm::StringMap<std::string> Files;
+  llvm::StringMap<time_t> Timestamps;
   MockCompilationDatabase CDB;
 };
 

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/TestFS.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TestFS.cpp Mon Jan  7 07:45:19 2019
@@ -14,37 +14,36 @@
 
 namespace clang {
 namespace clangd {
-using namespace llvm;
 
-IntrusiveRefCntPtr<vfs::FileSystem>
-buildTestFS(StringMap<std::string> const &Files,
-            StringMap<time_t> const &Timestamps) {
-  IntrusiveRefCntPtr<vfs::InMemoryFileSystem> MemFS(
-      new vfs::InMemoryFileSystem);
+llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
+buildTestFS(llvm::StringMap<std::string> const &Files,
+            llvm::StringMap<time_t> const &Timestamps) {
+  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> MemFS(
+      new llvm::vfs::InMemoryFileSystem);
   MemFS->setCurrentWorkingDirectory(testRoot());
   for (auto &FileAndContents : Files) {
-    StringRef File = FileAndContents.first();
+    llvm::StringRef File = FileAndContents.first();
     MemFS->addFile(
         File, Timestamps.lookup(File),
-        MemoryBuffer::getMemBufferCopy(FileAndContents.second, File));
+        llvm::MemoryBuffer::getMemBufferCopy(FileAndContents.second, File));
   }
   return MemFS;
 }
 
-MockCompilationDatabase::MockCompilationDatabase(StringRef Directory,
-                                                 StringRef RelPathPrefix)
+MockCompilationDatabase::MockCompilationDatabase(llvm::StringRef Directory,
+                                                 llvm::StringRef RelPathPrefix)
     : ExtraClangFlags({"-ffreestanding"}), Directory(Directory),
       RelPathPrefix(RelPathPrefix) {
   // -ffreestanding avoids implicit stdc-predef.h.
 }
 
-Optional<tooling::CompileCommand>
+llvm::Optional<tooling::CompileCommand>
 MockCompilationDatabase::getCompileCommand(PathRef File,
                                            ProjectInfo *Project) const {
   if (ExtraClangFlags.empty())
     return None;
 
-  auto FileName = sys::path::filename(File);
+  auto FileName = llvm::sys::path::filename(File);
 
   // Build the compile command.
   auto CommandLine = ExtraClangFlags;
@@ -54,16 +53,17 @@ MockCompilationDatabase::getCompileComma
     CommandLine.push_back(File);
   } else {
     // Build a relative path using RelPathPrefix.
-    SmallString<32> RelativeFilePath(RelPathPrefix);
-    sys::path::append(RelativeFilePath, FileName);
+    llvm::SmallString<32> RelativeFilePath(RelPathPrefix);
+    llvm::sys::path::append(RelativeFilePath, FileName);
     CommandLine.push_back(RelativeFilePath.str());
   }
 
   if (Project)
     Project->SourceRoot = Directory;
-  return {tooling::CompileCommand(
-      Directory != StringRef() ? Directory : sys::path::parent_path(File),
-      FileName, std::move(CommandLine), "")};
+  return {tooling::CompileCommand(Directory != llvm::StringRef()
+                                      ? Directory
+                                      : llvm::sys::path::parent_path(File),
+                                  FileName, std::move(CommandLine), "")};
 }
 
 const char *testRoot() {
@@ -75,12 +75,12 @@ const char *testRoot() {
 }
 
 std::string testPath(PathRef File) {
-  assert(sys::path::is_relative(File) && "FileName should be relative");
+  assert(llvm::sys::path::is_relative(File) && "FileName should be relative");
 
-  SmallString<32> NativeFile = File;
-  sys::path::native(NativeFile);
-  SmallString<32> Path;
-  sys::path::append(Path, testRoot(), NativeFile);
+  llvm::SmallString<32> NativeFile = File;
+  llvm::sys::path::native(NativeFile);
+  llvm::SmallString<32> Path;
+  llvm::sys::path::append(Path, testRoot(), NativeFile);
   return Path.str();
 }
 
@@ -91,29 +91,32 @@ class TestScheme : public URIScheme {
 public:
   static const char *Scheme;
 
-  Expected<std::string> getAbsolutePath(StringRef /*Authority*/, StringRef Body,
-                                        StringRef HintPath) const override {
+  llvm::Expected<std::string>
+  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
+                  llvm::StringRef HintPath) const override {
     if (!HintPath.startswith(testRoot()))
-      return make_error<StringError>(
+      return llvm::make_error<llvm::StringError>(
           "Hint path doesn't start with test root: " + HintPath,
-          inconvertibleErrorCode());
+          llvm::inconvertibleErrorCode());
     if (!Body.consume_front("/"))
-      return make_error<StringError>(
+      return llvm::make_error<llvm::StringError>(
           "Body of an unittest: URI must start with '/'",
-          inconvertibleErrorCode());
-    SmallString<16> Path(Body.begin(), Body.end());
-    sys::path::native(Path);
+          llvm::inconvertibleErrorCode());
+    llvm::SmallString<16> Path(Body.begin(), Body.end());
+    llvm::sys::path::native(Path);
     return testPath(Path);
   }
 
-  Expected<URI> uriFromAbsolutePath(StringRef AbsolutePath) const override {
-    StringRef Body = AbsolutePath;
+  llvm::Expected<URI>
+  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
+    llvm::StringRef Body = AbsolutePath;
     if (!Body.consume_front(testRoot()))
-      return make_error<StringError>(AbsolutePath + "does not start with " +
-                                         testRoot(),
-                                     inconvertibleErrorCode());
+      return llvm::make_error<llvm::StringError>(
+          AbsolutePath + "does not start with " + testRoot(),
+          llvm::inconvertibleErrorCode());
 
-    return URI(Scheme, /*Authority=*/"", sys::path::convert_to_slash(Body));
+    return URI(Scheme, /*Authority=*/"",
+               llvm::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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/TestIndex.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TestIndex.cpp Mon Jan  7 07:45:19 2019
@@ -9,15 +9,14 @@
 
 #include "TestIndex.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
-Symbol symbol(StringRef QName) {
+Symbol symbol(llvm::StringRef QName) {
   Symbol Sym;
   Sym.ID = SymbolID(QName.str());
   size_t Pos = QName.rfind("::");
-  if (Pos == StringRef::npos) {
+  if (Pos == llvm::StringRef::npos) {
     Sym.Name = QName;
     Sym.Scope = "";
   } else {
@@ -29,7 +28,7 @@ Symbol symbol(StringRef QName) {
 
 SymbolSlab generateSymbols(std::vector<std::string> QualifiedNames) {
   SymbolSlab::Builder Slab;
-  for (StringRef QName : QualifiedNames)
+  for (llvm::StringRef QName : QualifiedNames)
     Slab.insert(symbol(QName));
   return std::move(Slab).build();
 }
@@ -57,7 +56,8 @@ 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, ArrayRef<SymbolID> IDs) {
+std::vector<std::string> lookup(const SymbolIndex &I,
+                                llvm::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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/TestTU.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TestTU.cpp Mon Jan  7 07:45:19 2019
@@ -16,7 +16,6 @@
 #include "clang/Frontend/PCHContainerOperations.h"
 #include "clang/Frontend/Utils.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -67,7 +66,7 @@ std::unique_ptr<SymbolIndex> TestTU::ind
   return std::move(Idx);
 }
 
-const Symbol &findSymbol(const SymbolSlab &Slab, StringRef QName) {
+const Symbol &findSymbol(const SymbolSlab &Slab, llvm::StringRef QName) {
   const Symbol *Result = nullptr;
   for (const Symbol &S : Slab) {
     if (QName != (S.Scope + S.Name).str())
@@ -88,13 +87,13 @@ const Symbol &findSymbol(const SymbolSla
   return *Result;
 }
 
-const NamedDecl &findDecl(ParsedAST &AST, StringRef QName) {
-  SmallVector<StringRef, 4> Components;
+const NamedDecl &findDecl(ParsedAST &AST, llvm::StringRef QName) {
+  llvm::SmallVector<llvm::StringRef, 4> Components;
   QName.split(Components, "::");
 
   auto &Ctx = AST.getASTContext();
   auto LookupDecl = [&Ctx](const DeclContext &Scope,
-                           StringRef Name) -> const NamedDecl & {
+                           llvm::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");
@@ -113,7 +112,7 @@ const NamedDecl &findDecl(ParsedAST &AST
                           std::function<bool(const NamedDecl &)> Filter) {
   struct Visitor : RecursiveASTVisitor<Visitor> {
     decltype(Filter) F;
-    SmallVector<const NamedDecl *, 1> Decls;
+    llvm::SmallVector<const NamedDecl *, 1> Decls;
     bool VisitNamedDecl(const NamedDecl *ND) {
       if (F(*ND))
         Decls.push_back(ND);
@@ -129,7 +128,7 @@ const NamedDecl &findDecl(ParsedAST &AST
   return *Visitor.Decls.front();
 }
 
-const NamedDecl &findUnqualifiedDecl(ParsedAST &AST, StringRef Name) {
+const NamedDecl &findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name) {
   return findDecl(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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp Mon Jan  7 07:45:19 2019
@@ -17,32 +17,32 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
 
 MATCHER_P(StringNode, Val, "") {
-  if (arg->getType() != yaml::Node::NK_Scalar) {
+  if (arg->getType() != llvm::yaml::Node::NK_Scalar) {
     *result_listener << "is a " << arg->getVerbatimTag();
     return false;
   }
-  SmallString<32> S;
-  return Val == static_cast<yaml::ScalarNode *>(arg)->getValue(S);
+  llvm::SmallString<32> S;
+  return Val == static_cast<llvm::yaml::ScalarNode *>(arg)->getValue(S);
 }
 
 // Checks that N is a Mapping (JS object) with the expected scalar properties.
 // The object must have all the Expected properties, but may have others.
-bool VerifyObject(yaml::Node &N, std::map<std::string, std::string> Expected) {
-  auto *M = dyn_cast<yaml::MappingNode>(&N);
+bool VerifyObject(llvm::yaml::Node &N,
+                  std::map<std::string, std::string> Expected) {
+  auto *M = llvm::dyn_cast<llvm::yaml::MappingNode>(&N);
   if (!M) {
     ADD_FAILURE() << "Not an object";
     return false;
   }
   bool Match = true;
-  SmallString<32> Tmp;
+  llvm::SmallString<32> Tmp;
   for (auto &Prop : *M) {
-    auto *K = dyn_cast_or_null<yaml::ScalarNode>(Prop.getKey());
+    auto *K = llvm::dyn_cast_or_null<llvm::yaml::ScalarNode>(Prop.getKey());
     if (!K)
       continue;
     std::string KS = K->getValue(Tmp).str();
@@ -50,7 +50,7 @@ bool VerifyObject(yaml::Node &N, std::ma
     if (I == Expected.end())
       continue; // Ignore properties with no assertion.
 
-    auto *V = dyn_cast_or_null<yaml::ScalarNode>(Prop.getValue());
+    auto *V = llvm::dyn_cast_or_null<llvm::yaml::ScalarNode>(Prop.getValue());
     if (!V) {
       ADD_FAILURE() << KS << " is not a string";
       Match = false;
@@ -73,7 +73,7 @@ TEST(TraceTest, SmokeTest) {
   // Capture some events.
   std::string JSON;
   {
-    raw_string_ostream OS(JSON);
+    llvm::raw_string_ostream OS(JSON);
     auto JSONTracer = trace::createJSONTracer(OS);
     trace::Session Session(*JSONTracer);
     {
@@ -83,15 +83,15 @@ TEST(TraceTest, SmokeTest) {
   }
 
   // Get the root JSON object using the YAML parser.
-  SourceMgr SM;
-  yaml::Stream Stream(JSON, SM);
+  llvm::SourceMgr SM;
+  llvm::yaml::Stream Stream(JSON, SM);
   auto Doc = Stream.begin();
   ASSERT_NE(Doc, Stream.end());
-  auto *Root = dyn_cast_or_null<yaml::MappingNode>(Doc->getRoot());
+  auto *Root = llvm::dyn_cast_or_null<llvm::yaml::MappingNode>(Doc->getRoot());
   ASSERT_NE(Root, nullptr) << "Root should be an object";
 
   // Check whether we expect thread name events on this platform.
-  SmallString<32> ThreadName;
+  llvm::SmallString<32> ThreadName;
   get_thread_name(ThreadName);
   bool ThreadsHaveNames = !ThreadName.empty();
 
@@ -105,7 +105,8 @@ TEST(TraceTest, SmokeTest) {
   EXPECT_THAT(Prop->getValue(), StringNode("ns"));
   ASSERT_NE(++Prop, Root->end()) << "Expected traceEvents property";
   EXPECT_THAT(Prop->getKey(), StringNode("traceEvents"));
-  auto *Events = dyn_cast_or_null<yaml::SequenceNode>(Prop->getValue());
+  auto *Events =
+      llvm::dyn_cast_or_null<llvm::yaml::SequenceNode>(Prop->getValue());
   ASSERT_NE(Events, nullptr) << "traceEvents should be an array";
   auto Event = Events->begin();
   ASSERT_NE(Event, Events->end()) << "Expected process name";

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/URITests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/URITests.cpp Mon Jan  7 07:45:19 2019
@@ -13,7 +13,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 
@@ -29,14 +28,15 @@ 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(StringRef AbsolutePath, StringRef Scheme = "file") {
+std::string createOrDie(llvm::StringRef AbsolutePath,
+                        llvm::StringRef Scheme = "file") {
   auto Uri = URI::create(AbsolutePath, Scheme);
   if (!Uri)
     llvm_unreachable(toString(Uri.takeError()).c_str());
   return Uri->toString();
 }
 
-URI parseOrDie(StringRef Uri) {
+URI parseOrDie(llvm::StringRef Uri) {
   auto U = URI::parse(Uri);
   if (!U)
     llvm_unreachable(toString(U.takeError()).c_str());
@@ -61,7 +61,7 @@ TEST(PercentEncodingTest, Decode) {
   EXPECT_EQ(parseOrDie("x:a:b%3bc").body(), "a:b;c");
 }
 
-std::string resolveOrDie(const URI &U, StringRef HintPath = "") {
+std::string resolveOrDie(const URI &U, llvm::StringRef HintPath = "") {
   auto Path = URI::resolve(U, HintPath);
   if (!Path)
     llvm_unreachable(toString(Path.takeError()).c_str());
@@ -137,7 +137,8 @@ TEST(URITest, Resolve) {
             testPath("a"));
 }
 
-std::string resolvePathOrDie(StringRef AbsPath, StringRef HintPath = "") {
+std::string resolvePathOrDie(llvm::StringRef AbsPath,
+                             llvm::StringRef HintPath = "") {
   auto Path = URI::resolvePath(AbsPath, HintPath);
   if (!Path)
     llvm_unreachable(toString(Path.takeError()).c_str());

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=350531&r1=350530&r2=350531&view=diff
==============================================================================
--- clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp Mon Jan  7 07:45:19 2019
@@ -21,7 +21,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using namespace llvm;
 namespace clang {
 namespace clangd {
 namespace {
@@ -379,7 +378,7 @@ int [[bar_not_preamble]];
   // Make the compilation paths appear as ../src/foo.cpp in the compile
   // commands.
   SmallString<32> RelPathPrefix("..");
-  sys::path::append(RelPathPrefix, "src");
+  llvm::sys::path::append(RelPathPrefix, "src");
   std::string BuildDir = testPath("build");
   MockCompilationDatabase CDB(BuildDir, RelPathPrefix);
 
@@ -1305,9 +1304,9 @@ TEST(FindReferences, NeedsIndex) {
 
 TEST(FindReferences, NoQueryForLocalSymbols) {
   struct RecordingIndex : public MemIndex {
-    mutable Optional<DenseSet<SymbolID>> RefIDs;
+    mutable Optional<llvm::DenseSet<SymbolID>> RefIDs;
     void refs(const RefsRequest &Req,
-              function_ref<void(const Ref &)>) const override {
+              llvm::function_ref<void(const Ref &)>) const override {
       RefIDs = Req.IDs;
     }
   };




More information about the cfe-commits mailing list