Index: clangd/ClangdLSPServer.cpp =================================================================== --- clangd/ClangdLSPServer.cpp +++ clangd/ClangdLSPServer.cpp @@ -100,7 +100,7 @@ reply(json::obj{ {{"capabilities", json::obj{ - {"textDocumentSync", 1}, + {"textDocumentSync", (int)TextDocumentSyncKind::Incremental}, {"documentFormattingProvider", true}, {"documentRangeFormattingProvider", true}, {"documentOnTypeFormattingProvider", @@ -147,25 +147,25 @@ PathRef File = Params.textDocument.uri.file(); std::string &Contents = Params.textDocument.text; - DraftMgr.updateDraft(File, Contents); + DraftMgr.addDraft(File, Contents); Server.addDocument(File, Contents, WantDiagnostics::Yes); } void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) { - if (Params.contentChanges.size() != 1) - return replyError(ErrorCode::InvalidParams, - "can only apply one change at a time"); auto WantDiags = WantDiagnostics::Auto; if (Params.wantDiagnostics.hasValue()) WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes : WantDiagnostics::No; PathRef File = Params.textDocument.uri.file(); - std::string &Contents = Params.contentChanges[0].text; + llvm::Expected Contents = + DraftMgr.updateDraft(File, Params.contentChanges); + if (!Contents) { + log(llvm::toString(Contents.takeError())); + return; + } - // We only support full syncing right now. - DraftMgr.updateDraft(File, Contents); - Server.addDocument(File, Contents, WantDiags); + Server.addDocument(File, *Contents, WantDiags); } void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) { Index: clangd/DraftStore.h =================================================================== --- clangd/DraftStore.h +++ clangd/DraftStore.h @@ -11,6 +11,7 @@ #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_DRAFTSTORE_H #include "Path.h" +#include "Protocol.h" #include "clang/Basic/LLVM.h" #include "llvm/ADT/StringMap.h" #include @@ -32,7 +33,13 @@ std::vector getActiveFiles() const; /// Replace contents of the draft for \p File with \p Contents. - void updateDraft(PathRef File, StringRef Contents); + void addDraft(PathRef File, StringRef Contents); + + /// Update the contents of the draft for \p File based on \p Changes. + /// \return The new version of the draft for \p File. + llvm::Expected + updateDraft(PathRef File, + llvm::ArrayRef Changes); /// Remove the draft from the store. void removeDraft(PathRef File); Index: clangd/DraftStore.cpp =================================================================== --- clangd/DraftStore.cpp +++ clangd/DraftStore.cpp @@ -8,6 +8,8 @@ //===----------------------------------------------------------------------===// #include "DraftStore.h" +#include "SourceCode.h" +#include "llvm/Support/Errc.h" using namespace clang; using namespace clang::clangd; @@ -32,12 +34,84 @@ return ResultVector; } -void DraftStore::updateDraft(PathRef File, StringRef Contents) { +void DraftStore::addDraft(PathRef File, StringRef Contents) { std::lock_guard Lock(Mutex); Drafts[File] = Contents; } +llvm::Expected DraftStore::updateDraft( + PathRef File, llvm::ArrayRef Changes) { + std::lock_guard Lock(Mutex); + + auto EntryIt = Drafts.find(File); + if (EntryIt == Drafts.end()) { + return llvm::make_error( + "Trying to do incremental update on non-added document: " + File, + llvm::errc::invalid_argument); + } + + std::string &Contents = EntryIt->second; + + for (const TextDocumentContentChangeEvent &Change : Changes) { + std::string NewContents; + + if (Change.range) { + const Position &Start = Change.range->start; + size_t StartIndex = positionToOffset(Contents, Start); + if (StartIndex > Contents.length()) { + return llvm::make_error( + llvm::formatv("Range's start position (line={0}, character={1}) is " + "out of range.", + Start.line, Start.character), + llvm::errc::invalid_argument); + } + + const Position &End = Change.range->end; + size_t EndIndex = positionToOffset(Contents, End); + if (EndIndex > Contents.length()) { + return llvm::make_error( + llvm::formatv("Range's end position (line={0}, character={1}) is " + "out of range.", + End.line, End.character), + llvm::errc::invalid_argument); + } + + if (EndIndex < StartIndex) { + return llvm::make_error( + llvm::formatv("Range's end position (line={0}, character={1}) is " + "before start position (line={2}, character={3}).", + End.line, End.character, Start.line, Start.character), + llvm::errc::invalid_argument); + } + + if (Change.rangeLength && + (ssize_t)(EndIndex - StartIndex) != *Change.rangeLength) { + return llvm::make_error( + llvm::formatv("Change's rangeLength ({0}) doesn't match the " + "computed range length ({1}).", + *Change.rangeLength, EndIndex - StartIndex), + llvm::errc::invalid_argument); + } + + NewContents.reserve(StartIndex + Change.text.length() + + (Contents.length() - EndIndex)); + + NewContents = Contents.substr(0, StartIndex); + NewContents += Change.text; + + if (EndIndex < Contents.length()) + NewContents += Contents.substr(EndIndex); + } else { + NewContents = Change.text; + } + + Contents = std::move(NewContents); + } + + return Contents; +} + void DraftStore::removeDraft(PathRef File) { std::lock_guard Lock(Mutex); Index: clangd/Protocol.h =================================================================== --- clangd/Protocol.h +++ clangd/Protocol.h @@ -197,6 +197,20 @@ using ShutdownParams = NoParams; using ExitParams = NoParams; +/// Defines how the host (editor) should sync document changes to the language +/// server. +enum class TextDocumentSyncKind { + /// Documents should not be synced at all. + None = 0, + + /// Documents are synced by always sending the full content of the document. + Full = 1, + + /// Documents are synced by sending the full content on open. After that + /// only incremental updates to the document are send. + Incremental = 2, +}; + struct CompletionItemClientCapabilities { /// Client supports snippets as insert text. bool snippetSupport = false; @@ -287,7 +301,13 @@ bool fromJSON(const json::Expr &, DidCloseTextDocumentParams &); struct TextDocumentContentChangeEvent { - /// The new text of the document. + /// The range of the document that changed. + llvm::Optional range; + + /// The length of the range that got replaced. + llvm::Optional rangeLength; + + /// The new text of the range/document. std::string text; }; bool fromJSON(const json::Expr &, TextDocumentContentChangeEvent &); Index: clangd/Protocol.cpp =================================================================== --- clangd/Protocol.cpp +++ clangd/Protocol.cpp @@ -248,7 +248,8 @@ bool fromJSON(const json::Expr &Params, TextDocumentContentChangeEvent &R) { json::ObjectMapper O(Params); - return O && O.map("text", R.text); + return O && O.map("range", R.range) && O.map("rangeLength", R.rangeLength) && + O.map("text", R.text); } bool fromJSON(const json::Expr &Params, FormattingOptions &R) { Index: test/clangd/initialize-params-invalid.test =================================================================== --- test/clangd/initialize-params-invalid.test +++ test/clangd/initialize-params-invalid.test @@ -36,7 +36,7 @@ # CHECK-NEXT: "," # CHECK-NEXT: ] # CHECK-NEXT: }, -# CHECK-NEXT: "textDocumentSync": 1 +# CHECK-NEXT: "textDocumentSync": 2 # CHECK-NEXT: } # CHECK-NEXT: } --- Index: test/clangd/initialize-params.test =================================================================== --- test/clangd/initialize-params.test +++ test/clangd/initialize-params.test @@ -36,7 +36,7 @@ # CHECK-NEXT: "," # CHECK-NEXT: ] # CHECK-NEXT: }, -# CHECK-NEXT: "textDocumentSync": 1 +# CHECK-NEXT: "textDocumentSync": 2 # CHECK-NEXT: } # CHECK-NEXT: } --- Index: unittests/clangd/CMakeLists.txt =================================================================== --- unittests/clangd/CMakeLists.txt +++ unittests/clangd/CMakeLists.txt @@ -15,6 +15,7 @@ CodeCompleteTests.cpp CodeCompletionStringsTests.cpp ContextTests.cpp + DraftStoreTests.cpp FileIndexTests.cpp FuzzyMatchTests.cpp HeadersTests.cpp Index: unittests/clangd/DraftStoreTests.cpp =================================================================== --- /dev/null +++ unittests/clangd/DraftStoreTests.cpp @@ -0,0 +1,235 @@ +//===-- DraftStoreTests.cpp - Clangd unit tests -----------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "Annotations.h" +#include "DraftStore.h" +#include "SourceCode.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace clang { +namespace clangd { +namespace { + +using namespace llvm; + +struct IncrementalTestStep { + StringRef Src; + StringRef Contents; +}; + +static int rangeLength(StringRef Code, const Range &Rng) { + size_t Start = positionToOffset(Code, Rng.start); + size_t End = positionToOffset(Code, Rng.end); + + assert(Start <= Code.size()); + assert(End <= Code.size()); + + return End - Start; +} + +// Send the changes one by one to updateDraft, verify the intermediate results. + +static void stepByStep(llvm::ArrayRef Steps) { + DraftStore DS; + Annotations InitialSrc(Steps.front().Src); + const char Path[] = "/hello.cpp"; + + // Set the initial content. + DS.addDraft(Path, InitialSrc.code()); + + 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; + TextDocumentContentChangeEvent Event{ + SrcBefore.range(), + rangeLength(SrcBefore.code(), SrcBefore.range()), + Contents.str(), + }; + + llvm::Expected Result = DS.updateDraft(Path, {Event}); + EXPECT_TRUE(!!Result); + EXPECT_EQ(*Result, SrcAfter.code()); + EXPECT_EQ(*DS.getDraft(Path), SrcAfter.code()); + } +} + +// Send all the changes at once to updateDraft, check only the final result. + +static void allAtOnce(llvm::ArrayRef Steps) { + DraftStore DS; + Annotations InitialSrc(Steps.front().Src); + Annotations FinalSrc(Steps.back().Src); + const char Path[] = "/hello.cpp"; + std::vector Changes; + + for (size_t i = 0; i < Steps.size() - 1; i++) { + Annotations Src(Steps[i].Src); + StringRef Contents = Steps[i].Contents; + + Changes.push_back({ + Src.range(), + rangeLength(Src.code(), Src.range()), + Contents.str(), + }); + } + + // Set the initial content. + DS.addDraft(Path, InitialSrc.code()); + + llvm::Expected Result = DS.updateDraft(Path, Changes); + + EXPECT_TRUE(!!Result) << llvm::toString(Result.takeError()); + EXPECT_EQ(*Result, FinalSrc.code()); + EXPECT_EQ(*DS.getDraft(Path), FinalSrc.code()); +} + +TEST(DraftStoreIncrementalUpdateTest, Simple) { + // clang-format off + IncrementalTestStep Steps[] = + { + // Replace a range + { +R"cpp(static int +hello[[World]]() +{})cpp", + "Universe" + }, + // Delete a range + { +R"cpp(static int +hello[[Universe]]() +{})cpp", + "" + }, + // Add a range + { +R"cpp(static int +hello[[]]() +{})cpp", + "Monde" + }, + { +R"cpp(static int +helloMonde() +{})cpp", + "" + } + }; + // clang-format on + + stepByStep(Steps); + allAtOnce(Steps); +} + +TEST(DraftStoreIncrementalUpdateTest, MultiLine) { + // clang-format off + IncrementalTestStep Steps[] = + { + // Replace a range + { +R"cpp(static [[int +helloWorld]]() +{})cpp", +R"cpp(char +welcome)cpp" + }, + // Delete a range + { +R"cpp(static char[[ +welcome]]() +{})cpp", + "" + }, + // Add a range + { +R"cpp(static char[[]]() +{})cpp", + R"cpp( +cookies)cpp" + }, + // Replace the whole file + { +R"cpp([[static char +cookies() +{}]])cpp", + R"cpp(#include +)cpp" + }, + // Delete the whole file + { + R"cpp([[#include +]])cpp", + "", + }, + // Add something to an empty file + { + "[[]]", + R"cpp(int main() { +)cpp", + }, + { + R"cpp(int main() { +)cpp", + "" + } + }; + // clang-format on + + stepByStep(Steps); + allAtOnce(Steps); +} + +TEST(DraftStoreIncrementalUpdateTest, WrongRangeLength) { + DraftStore DS; + Path File = "foo.cpp"; + + DS.addDraft(File, "int main() {}\n"); + + TextDocumentContentChangeEvent Change; + Change.range.emplace(); + Change.range->start.line = 0; + Change.range->start.character = 0; + Change.range->end.line = 0; + Change.range->end.character = 2; + Change.rangeLength = 10; + + llvm::Expected Result = DS.updateDraft(File, {Change}); + + EXPECT_TRUE(!Result); + EXPECT_EQ( + llvm::toString(Result.takeError()), + "Change's rangeLength (10) doesn't match the computed range length (2)."); +} + +TEST(DraftStoreIncrementalUpdateTest, EndBeforeStart) { + DraftStore DS; + Path File = "foo.cpp"; + + DS.addDraft(File, "int main() {}\n"); + + TextDocumentContentChangeEvent Change; + Change.range.emplace(); + Change.range->start.line = 0; + Change.range->start.character = 5; + Change.range->end.line = 0; + Change.range->end.character = 3; + + llvm::Expected Result = DS.updateDraft(File, {Change}); + + EXPECT_TRUE(!Result); + EXPECT_EQ(llvm::toString(Result.takeError()), + "Range's end position (line=0, character=3) is before start " + "position (line=0, character=5)."); +} + +} // namespace +} // namespace clangd +} // namespace clang