From 1d0e8840dd8cb2915306427f264da7e0ed947dc0 Mon Sep 17 00:00:00 2001 From: "devnull.exile" Date: Tue, 13 Oct 2026 12:01:41 +0300 Subject: [PATCH] fix(clangd): attach document version to publishDiagnostics publishDiagnosticsFor set PublishDiagnosticsParams::version only when llvm::to_integer failed, so numeric versions were dropped and non-numeric strings were sent as 0. Clients need the version to discard diagnostics computed for an older text state. Pass the version DraftStore assigned to the draft straight through as std::optional, which removes the inverted check. Like ClangdLSPServer, publish the synthesized draft version when the client omits one. updateDraft now takes and returns the integer version, so the module has a single version representation. Also clear published diagnostics when an incremental change fails to apply and the draft is dropped, tagged with the rejected edit's version, and honor wantDiagnostics=false on didChange. The clear ignores wantDiagnostics, since without a draft nothing would replace those diagnostics. Publishing and clearing share one notification builder that uses the canonical file URI. Validation: PseudoModuleTests (77), ClangPseudoTests (46) and check-clang-pseudo (153) pass; test_lsp.py passes against the CI clangd build and fails with the unfixed plugin. Fixes #5 --- README.md | 2 +- clangd/PseudoModule.cpp | 72 ++++++++----- clangd/PseudoModule.h | 15 ++- test_lsp.py | 67 ++++++++++--- unittests/clangd/PseudoModuleTests.cpp | 133 +++++++++++++++++++++++++ 5 files changed, 243 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 0568e3d..472281e 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ clangd -enable-config=0 -check=file.cpp -load=/path/to/libclangd_pseudo.so 1. Upstream `clangd` (on `main`) supports loading dynamic plugins via `-load`. 2. When loaded, `libclangd_pseudo` registers itself into `clangd::FeatureModuleRegistry`. 3. Upon LSP client initialization, the module intercepts document opening (`textDocument/didOpen`) and edits (`textDocument/didChange`). -4. It parses the code with the C++ GLR pseudo-parser and publishes immediate syntax, bracket, and preprocessor diagnostics via `textDocument/publishDiagnostics`. +4. It parses the code with the C++ GLR pseudo-parser and publishes immediate syntax, bracket, and preprocessor diagnostics via `textDocument/publishDiagnostics`. Each notification carries the document version it was computed for, so clients can drop stale results; a `didChange` with clangd's `wantDiagnostics: false` extension skips publishing. --- diff --git a/clangd/PseudoModule.cpp b/clangd/PseudoModule.cpp index fc7b65e..de68ed2 100644 --- a/clangd/PseudoModule.cpp +++ b/clangd/PseudoModule.cpp @@ -24,6 +24,7 @@ #include "clang/Basic/CharInfo.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/TokenKinds.h" +#include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Error.h" #include "llvm/Support/Path.h" @@ -174,21 +175,45 @@ PseudoModule::getAST(PathRef File, llvm::StringRef Code, return clangd::getAST(File, Code, R); } +// LSP versions are integers, DraftStore treats them as opaque strings. static std::string encodeVersion(std::optional LSPVersion) { return LSPVersion ? std::to_string(*LSPVersion) : ""; } -void PseudoModule::updateDraft(PathRef File, llvm::StringRef Contents, - llvm::StringRef Version) { - DraftMgr.addDraft(File, Version, Contents); +static std::optional decodeVersion(llvm::StringRef Encoded) { + int64_t Result; + if (llvm::to_integer(Encoded, Result, 10)) + return Result; + if (!Encoded.empty()) + elog("unexpected non-numeric version {0}", Encoded); + return std::nullopt; +} + +std::optional PseudoModule::updateDraft(PathRef File, + llvm::StringRef Contents, + std::optional Version) { + return decodeVersion( + DraftMgr.addDraft(File, encodeVersion(Version), Contents)); } void PseudoModule::removeDraft(PathRef File) { DraftMgr.removeDraft(File); } +void PseudoModule::sendDiagnostics(PathRef File, std::optional Version, + std::vector Diags) { + if (!PublishDiagnostics) + return; + PublishDiagnosticsParams Notification; + Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File); + Notification.diagnostics = std::move(Diags); + Notification.version = Version; + PublishDiagnostics(Notification); +} + void PseudoModule::publishDiagnosticsFor(PathRef File, llvm::StringRef Contents, - llvm::StringRef Version) { + std::optional Version) { + // Skip the parse when no client is listening. if (!PublishDiagnostics) return; auto Diags = getDiagnostics(File, Contents); @@ -196,22 +221,18 @@ void PseudoModule::publishDiagnosticsFor(PathRef File, llvm::StringRef Contents, consumeError(Diags.takeError()); return; } - PublishDiagnosticsParams Notification; - Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File); - Notification.diagnostics = std::move(*Diags); - if (!Version.empty()) { - int64_t V = 0; - if (!llvm::to_integer(Version, V)) - Notification.version = V; - } - PublishDiagnostics(Notification); + sendDiagnostics(File, Version, std::move(*Diags)); +} + +void PseudoModule::clearDiagnosticsFor(PathRef File, + std::optional Version) { + sendDiagnostics(File, Version, {}); } void PseudoModule::onDocumentDidOpen(const DidOpenTextDocumentParams &Params) { PathRef File = Params.textDocument.uri.file(); const std::string &Contents = Params.textDocument.text; - std::string Version = encodeVersion(Params.textDocument.version); - DraftMgr.addDraft(File, Version, Contents); + auto Version = updateDraft(File, Contents, Params.textDocument.version); publishDiagnosticsFor(File, Contents, Version); } @@ -226,26 +247,25 @@ void PseudoModule::onDocumentDidChange( std::string NewCode = *Draft->Contents; for (const auto &Change : Params.contentChanges) { if (auto Err = applyChange(NewCode, Change)) { - DraftMgr.removeDraft(File); + removeDraft(File); elog("Failed to update {0}: {1}", File, std::move(Err)); + // Clear even if wantDiagnostics is false: without a draft, later + // changes are ignored and nothing would replace these diagnostics. + clearDiagnosticsFor(File, Params.textDocument.version); return; } } - std::string Version = encodeVersion(Params.textDocument.version); - DraftMgr.addDraft(File, Version, NewCode); - publishDiagnosticsFor(File, NewCode, Version); + auto Version = updateDraft(File, NewCode, Params.textDocument.version); + // forceRebuild needs no handling: every publish is a fresh parse. + if (Params.wantDiagnostics.value_or(true)) + publishDiagnosticsFor(File, NewCode, Version); } void PseudoModule::onDocumentDidClose( const DidCloseTextDocumentParams &Params) { PathRef File = Params.textDocument.uri.file(); - DraftMgr.removeDraft(File); - if (PublishDiagnostics) { - PublishDiagnosticsParams Notification; - Notification.uri = Params.textDocument.uri; - Notification.diagnostics = {}; - PublishDiagnostics(Notification); - } + removeDraft(File); + clearDiagnosticsFor(File); } void PseudoModule::initializeLSP(LSPBinder &Bind, diff --git a/clangd/PseudoModule.h b/clangd/PseudoModule.h index ece2345..c976514 100644 --- a/clangd/PseudoModule.h +++ b/clangd/PseudoModule.h @@ -29,6 +29,7 @@ #include "llvm/Support/VirtualFileSystem.h" #include #include +#include #include #include @@ -57,11 +58,16 @@ class PseudoModule final : public FeatureModule { void onDocumentDidChange(const DidChangeTextDocumentParams &Params); void onDocumentDidClose(const DidCloseTextDocumentParams &Params); - void updateDraft(PathRef File, llvm::StringRef Contents, - llvm::StringRef Version = ""); + /// Stores \p Contents as the draft for \p File and returns its version, + /// which DraftStore assigns when the client did not send one. + std::optional + updateDraft(PathRef File, llvm::StringRef Contents, + std::optional Version = std::nullopt); void removeDraft(PathRef File); void publishDiagnosticsFor(PathRef File, llvm::StringRef Contents, - llvm::StringRef Version = ""); + std::optional Version = std::nullopt); + void clearDiagnosticsFor(PathRef File, + std::optional Version = std::nullopt); void setEnabled(bool E) { Enabled = E; } bool isEnabled() const { return Enabled; } @@ -192,6 +198,9 @@ class PseudoModule final : public FeatureModule { llvm::IntrusiveRefCntPtr getFS() const; private: + void sendDiagnostics(PathRef File, std::optional Version, + std::vector Diags); + void onCustomPseudoSymbols(const DocumentSymbolParams &Params, Callback> Reply); diff --git a/test_lsp.py b/test_lsp.py index 5473fe5..0f3445b 100644 --- a/test_lsp.py +++ b/test_lsp.py @@ -50,6 +50,15 @@ def read_rpc(q, timeout=5): except queue.Empty: return None +def next_publish(q, timeout=5): + """Returns the params of the next publishDiagnostics, or None on timeout.""" + end = time.time() + timeout + while time.time() < end: + msg = read_rpc(q, timeout=max(0.1, end - time.time())) + if msg and msg.get("method") == "textDocument/publishDiagnostics": + return msg.get("params", {}) + return None + def main(): if len(sys.argv) < 2: print("Usage: test_lsp.py [path-to-clangd]") @@ -109,18 +118,48 @@ def main(): t0 = time.time() diags1 = [] - while time.time() - t0 < 5: - msg = read_rpc(msg_queue, timeout=1) - if not msg: - continue - if msg.get("method") == "textDocument/publishDiagnostics": - diags1.extend(msg.get("params", {}).get("diagnostics", [])) - if any("syntax error" in d.get("message", "") for d in diags1): - break + syntax_error_version1 = None + while (params := next_publish(msg_queue)) is not None: + diags = params.get("diagnostics", []) + diags1.extend(diags) + if any("syntax error" in d.get("message", "") for d in diags): + syntax_error_version1 = params.get("version") + break print(f"[OK] Received {len(diags1)} diagnostics for test1 in {time.time()-t0:.3f}s:") for d in diags1: print(f" - {d.get('range')}: {d.get('message')}") assert any("syntax error" in d.get("message", "") for d in diags1), "Expected syntax error diagnostic" + assert syntax_error_version1 == 1, \ + f"Expected syntax error diagnostics published for version 1, got {syntax_error_version1}" + + # 2b. Diagnostics follow the document version across didChange + def change_test1(version, **extra): + text_document = {"uri": test1_uri} + if version is not None: + text_document["version"] = version + send_rpc(proc, { + "jsonrpc": "2.0", + "method": "textDocument/didChange", + "params": { + "textDocument": text_document, + "contentChanges": [{"text": test1_code}], + **extra + } + }) + + change_test1(2) + published = next_publish(msg_queue) + assert published and published.get("version") == 2, \ + f"Expected diagnostics for version 2 after didChange, got {published}" + print("[OK] didChange published diagnostics for version 2") + + # Sent back to back: a publish for version 3 would arrive first. + change_test1(3, wantDiagnostics=False) + change_test1(None) + published = next_publish(msg_queue) + assert published and published.get("version") == 4, \ + f"Expected wantDiagnostics=false to skip version 3 and a synthesized version 4, got {published}" + print("[OK] wantDiagnostics=false skipped publishing; omitted version synthesized as 4") # 3. Test preprocessor recovery diagnostics on didOpen test2_uri = pathlib.Path(os.path.abspath("test2.cpp")).as_uri() @@ -140,14 +179,10 @@ def main(): t0 = time.time() diags2 = [] - while time.time() - t0 < 5: - msg = read_rpc(msg_queue, timeout=1) - if not msg: - continue - if msg.get("method") == "textDocument/publishDiagnostics": - diags2.extend(msg.get("params", {}).get("diagnostics", [])) - if len(diags2) > 0: - break + while (params := next_publish(msg_queue)) is not None: + diags2.extend(params.get("diagnostics", [])) + if diags2: + break print(f"[OK] Received {len(diags2)} diagnostics for test2 in {time.time()-t0:.3f}s:") for d in diags2: print(f" - {d.get('range')}: {d.get('message')}") diff --git a/unittests/clangd/PseudoModuleTests.cpp b/unittests/clangd/PseudoModuleTests.cpp index 2883ed4..08352dc 100644 --- a/unittests/clangd/PseudoModuleTests.cpp +++ b/unittests/clangd/PseudoModuleTests.cpp @@ -3933,6 +3933,139 @@ TEST(PseudoModuleTest, DocumentDraftLifecycleAndDiagnostics) { EXPECT_EQ(Mod.getDocument(File), ""); } +class RecordingOutgoing : public LSPBinder::RawOutgoing { +public: + void callMethod(llvm::StringRef Method, llvm::json::Value Params, + Callback Reply) override { + Reply(llvm::make_error("unexpected call", + ErrorCode::InternalError)); + } + void notify(llvm::StringRef Method, llvm::json::Value Params) override { + Notifications.emplace_back(Method.str(), std::move(Params)); + } + + std::vector> Notifications; +}; + +class PseudoModuleLSPTest : public ::testing::Test { +protected: + PseudoModuleLSPTest() : Bind(Handlers, Out) { + Mod.setPseudoOnly(true); + llvm::json::Object ServerCaps; + Mod.initializeLSP(Bind, llvm::json::Object{}, ServerCaps); + } + + void open(llvm::StringRef Code, std::optional Version) { + DidOpenTextDocumentParams Params; + Params.textDocument.uri = URI; + Params.textDocument.version = Version; + Params.textDocument.text = Code.str(); + Mod.onDocumentDidOpen(Params); + } + + void change(TextDocumentContentChangeEvent Change, + std::optional Version, + std::optional WantDiagnostics = std::nullopt) { + DidChangeTextDocumentParams Params; + Params.textDocument.uri = URI; + Params.textDocument.version = Version; + Params.contentChanges.push_back(std::move(Change)); + Params.wantDiagnostics = WantDiagnostics; + Mod.onDocumentDidChange(Params); + } + + void replaceAll(llvm::StringRef Code, std::optional Version, + std::optional WantDiagnostics = std::nullopt) { + TextDocumentContentChangeEvent Change; + Change.text = Code.str(); + change(std::move(Change), Version, WantDiagnostics); + } + + void close() { + DidCloseTextDocumentParams Params; + Params.textDocument.uri = URI; + Mod.onDocumentDidClose(Params); + } + + std::vector published() const { + std::vector Result; + for (const auto &[Method, Params] : Out.Notifications) + if (Method == "textDocument/publishDiagnostics") + Result.push_back(*Params.getAsObject()); + return Result; + } + + std::vector> publishedVersions() const { + std::vector> Versions; + for (const auto &Obj : published()) + Versions.push_back(Obj.getInteger("version")); + return Versions; + } + + static size_t diagnosticCount(const llvm::json::Object &Obj) { + const auto *Diags = Obj.getArray("diagnostics"); + return Diags ? Diags->size() : 0; + } + + // Mod is declared last so it is destroyed before the binder and recorder + // its publishDiagnostics callback refers to. + LSPBinder::RawHandlers Handlers; + RecordingOutgoing Out; + LSPBinder Bind; + PseudoModule Mod; + std::string File = testPath("versioned.cpp"); + URIForFile URI = URIForFile::canonicalize(File, File); +}; + +TEST_F(PseudoModuleLSPTest, PublishDiagnosticsCarriesDocumentVersion) { + open("int a = 1;", 1); + replaceAll("int a = 2;", 7); + close(); + // Clearing diagnostics on close is not tied to any text state. + EXPECT_THAT(publishedVersions(), ElementsAre(1, 7, std::nullopt)); +} + +TEST_F(PseudoModuleLSPTest, PublishDiagnosticsUsesDraftVersionWhenUnset) { + // Versions are optional in clangd; DraftStore assigns 0, 1, ... instead. + open("int a = 1;", std::nullopt); + replaceAll("int a = 2;", std::nullopt); + EXPECT_THAT(publishedVersions(), ElementsAre(0, 1)); +} + +TEST_F(PseudoModuleLSPTest, FailedChangeClearsDiagnostics) { + open("int f() {} {}\n", 1); + TextDocumentContentChangeEvent Bad; + Bad.range = Range{Position{42, 0}, Position{42, 1}}; + Bad.text = "x"; + change(std::move(Bad), 2); + + auto Published = published(); + ASSERT_EQ(Published.size(), 2u); + EXPECT_GT(diagnosticCount(Published[0]), 0u); + EXPECT_EQ(diagnosticCount(Published[1]), 0u); + // The clear is tied to the text state of the rejected edit. + EXPECT_EQ(Published[1].getInteger("version"), 2); +} + +TEST_F(PseudoModuleLSPTest, FailedChangeClearsDiagnosticsDespiteWantDiagnostics) { + open("int f() {} {}\n", 1); + TextDocumentContentChangeEvent Bad; + Bad.range = Range{Position{42, 0}, Position{42, 1}}; + Bad.text = "x"; + change(std::move(Bad), 2, /*WantDiagnostics=*/false); + + auto Published = published(); + ASSERT_EQ(Published.size(), 2u); + EXPECT_EQ(diagnosticCount(Published[1]), 0u); +} + +TEST_F(PseudoModuleLSPTest, WantDiagnosticsFalseSuppressesPublish) { + open("int a = 1;", 1); + replaceAll("int a = 2;", 2, /*WantDiagnostics=*/false); + replaceAll("int a = 3;", 3, /*WantDiagnostics=*/true); + EXPECT_THAT(publishedVersions(), ElementsAre(1, 3)); +} + TEST(PseudoModuleTest, DiagnosticsConditionalBranchMissingBrace) { PseudoModule Mod; llvm::StringRef Code = "#ifdef X\nvoid f(){\n#else\nvoid g()\n#endif\n}\n";