Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

---

Expand Down
72 changes: 46 additions & 26 deletions clangd/PseudoModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -174,44 +175,64 @@ 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<int64_t> 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<int64_t> decodeVersion(llvm::StringRef Encoded) {
Comment thread
ArcsinX marked this conversation as resolved.
Resolved
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<int64_t> PseudoModule::updateDraft(PathRef File,
llvm::StringRef Contents,
std::optional<int64_t> Version) {
return decodeVersion(
DraftMgr.addDraft(File, encodeVersion(Version), Contents));
}

void PseudoModule::removeDraft(PathRef File) {
DraftMgr.removeDraft(File);
}

void PseudoModule::sendDiagnostics(PathRef File, std::optional<int64_t> Version,
std::vector<Diagnostic> 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<int64_t> Version) {
// Skip the parse when no client is listening.
if (!PublishDiagnostics)
return;
auto Diags = getDiagnostics(File, Contents);
if (!Diags) {
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<int64_t> 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);
}

Expand All @@ -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,
Expand Down
15 changes: 12 additions & 3 deletions clangd/PseudoModule.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#include "llvm/Support/VirtualFileSystem.h"
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <vector>

Expand Down Expand Up @@ -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<int64_t>
updateDraft(PathRef File, llvm::StringRef Contents,
std::optional<int64_t> Version = std::nullopt);
void removeDraft(PathRef File);
void publishDiagnosticsFor(PathRef File, llvm::StringRef Contents,
llvm::StringRef Version = "");
std::optional<int64_t> Version = std::nullopt);
void clearDiagnosticsFor(PathRef File,
std::optional<int64_t> Version = std::nullopt);

void setEnabled(bool E) { Enabled = E; }
bool isEnabled() const { return Enabled; }
Expand Down Expand Up @@ -192,6 +198,9 @@ class PseudoModule final : public FeatureModule {
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> getFS() const;

private:
void sendDiagnostics(PathRef File, std::optional<int64_t> Version,
std::vector<Diagnostic> Diags);

void onCustomPseudoSymbols(const DocumentSymbolParams &Params,
Callback<std::vector<DocumentSymbol>> Reply);

Expand Down
67 changes: 51 additions & 16 deletions test_lsp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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_pseudo-plugin> [path-to-clangd]")
Expand Down Expand Up @@ -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()
Expand All @@ -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')}")
Expand Down
Loading
Loading