Files
lucisv/crates/lucisv_server/src/server/diagnostics.rs
T

241 lines
11 KiB
Rust

//! What the server says about a buffer's contents, and when.
//!
//! *When* is the change debounce: a `didChange` marks a buffer dirty and the
//! first thing that needs its analysis flushes it, so a typing burst costs
//! one reparse (`docs/features/change-debounce/README.md`). *What* is one
//! parse-and-lint pass, `diagnostics_of`, that both delivery models answer
//! from: the push (`publish`, gated so a pulling client is never pushed) and
//! the pull (`document_report`, `workspace_report`, stamped with the
//! generation — `docs/features/pull-diagnostics/README.md`).
use lsp_types::notification::{LogMessage, Notification as _, PublishDiagnostics};
use lsp_types::{
DocumentDiagnosticReport, FullDocumentDiagnosticReport, LogMessageParams, MessageType,
PreviousResultId, PublishDiagnosticsParams, RelatedFullDocumentDiagnosticReport,
RelatedUnchangedDocumentDiagnosticReport, UnchangedDocumentDiagnosticReport, Uri,
WorkspaceDiagnosticReport, WorkspaceDocumentDiagnosticReport,
WorkspaceFullDocumentDiagnosticReport, WorkspaceUnchangedDocumentDiagnosticReport,
};
use super::client::plural;
use super::Server;
use crate::diagnostics;
impl Server {
/// Replace a buffer's text, re-arming its `lucisv.toml` warning: the user
/// has moved on, and a config problem is worth saying once more.
pub(super) fn set_document(&mut self, uri: Uri, text: String) {
self.config_warnings.remove(&uri);
let was_large = self.workspace.document(&uri).is_some_and(|doc| doc.large);
self.workspace.set_document(uri.clone(), text);
self.generation += 1;
self.announce_fast_path(&uri, was_large);
}
/// Hold a buffer's newest text for later analysis. A change already held
/// is replaced in place, so the entry's position in the flush order — the
/// order the buffers were first dirtied in — survives a burst.
pub(super) fn mark_dirty(&mut self, uri: Uri, text: String) {
match self.dirty.iter_mut().find(|(pending, _)| *pending == uri) {
Some(entry) => entry.1 = text,
None => self.dirty.push((uri, text)),
}
}
/// Analyze and republish every dirty buffer, oldest first. One flush is
/// one `set_document` per buffer, so a whole typing burst costs one
/// reparse per buffer it touched instead of one per keystroke.
pub(super) fn flush_dirty(&mut self) {
if self.dirty.is_empty() {
return;
}
let started = self.timer();
let buffers = self.dirty.len();
for (uri, text) in std::mem::take(&mut self.dirty) {
self.set_document(uri.clone(), text);
crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri));
}
self.timed(started, |took| {
format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers))
});
}
/// Say once, in the output channel, that a buffer is on the large-file
/// fast path.
///
/// Once per *entry* into the mode, not once per notification: a keystroke
/// in a 100 MB buffer must not log a line, and a buffer edited past the
/// threshold mid-session must. Nothing is said on the way back out —
/// leaving the mode restores every answer, which is not news.
fn announce_fast_path(&self, uri: &Uri, was_large: bool) {
let Some(doc) = self.workspace.document(uri).filter(|doc| doc.large && !was_large) else {
return;
};
let what = match doc.path.as_deref() {
Some(path) => path.display().to_string(),
None => uri.as_str().to_string(),
};
let size = doc.text.len();
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::INFO,
message: format!(
"lucisv: large-file fast path: {what} ({size} bytes) — \
syntax highlighting only, nothing is parsed or indexed"
),
},
);
}
/// Everything the server has to say about a buffer — the one computation
/// both diagnostic models answer from. A buffer that is not open has
/// nothing said about it.
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
// The lint pass is given the project: the rule selection
// `lucisv.lint.*` and the buffer's `[lint]` table resolved to, and the
// index's identifier census, which is what lets the semantic rules
// default on here without accusing a signal another file reads
// (`docs/features/semantic-lints-on/`).
let run = crate::lint::LintRun::for_document(&self.workspace, doc);
self.report_config_problems(&run);
diagnostics::all_in(doc, &run)
}
/// Say, once, what this buffer's `lucisv.toml` asked for and did not get.
///
/// Once per (config file, entry), not once per pass: this runs on every
/// keystroke and every index rebuild. The words are the ones `lucisv
/// check` fails the run with, `<file>:<line>: <message>`, so one mistake
/// reads the same in CI and here — but nothing is fatal, the entry is
/// dropped and the buffer is still linted with everything understood
/// (§42.2). Logged, not shown: a typo in a checked-in config is not worth
/// a popup on every editor in the project.
fn report_config_problems(&self, run: &crate::lint::LintRun) {
let problems = run.config_problems();
if problems.is_empty() {
return;
}
// The borrow is released before anything is sent: `notify` takes
// `&self` and could otherwise reach a second borrow one day.
let unsaid = match self.lint_config_problems.try_borrow_mut() {
Ok(mut log) => log.unsaid(problems),
Err(_) => return,
};
for message in unsaid {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {message}; ignored"),
},
);
}
}
/// Publish everything known about a buffer — parse errors and lint
/// warnings — in one notification. Two publishes for one version would
/// leave only the second on screen, since LSP replaces rather than merges.
pub(super) fn publish(&self, uri: &Uri) {
// `send_diagnostics` would drop this anyway for a pulling client; the
// early return is so the parse+lint pass is not run for nobody, once
// per open buffer, on every index rebuild.
if self.abilities.pull_diagnostics || self.workspace.document(uri).is_none() {
return;
}
self.send_diagnostics(uri.clone(), self.diagnostics_of(uri));
}
/// Push one buffer's diagnostics — unless the client pulls them.
///
/// A client that advertised `textDocument.diagnostic` owns the timing and
/// the lifecycle of every diagnostic it shows: it asks when it wants them
/// and drops them when it closes the document, so a push would be a second
/// set of squiggles arriving on a schedule it did not choose. This is the
/// one gate that keeps the two models from ever running for one client —
/// the `didClose` clear goes through here too, for the same reason.
pub(super) fn send_diagnostics(&self, uri: Uri, diagnostics: Vec<lsp_types::Diagnostic>) {
if self.abilities.pull_diagnostics {
return;
}
let params = PublishDiagnosticsParams { uri, diagnostics, version: None };
self.notify(PublishDiagnostics::METHOD, params);
}
/// One buffer's diagnostics, or an unchanged report when nothing that
/// feeds them has moved since the client's last pull.
pub(super) fn document_report(
&self,
uri: &Uri,
previous: Option<String>,
) -> DocumentDiagnosticReport {
let result_id = self.result_id();
if previous.as_deref() == Some(result_id.as_str()) {
let unchanged = UnchangedDocumentDiagnosticReport { result_id };
return DocumentDiagnosticReport::Unchanged(RelatedUnchangedDocumentDiagnosticReport {
related_documents: None,
unchanged_document_diagnostic_report: unchanged,
});
}
let full = FullDocumentDiagnosticReport {
result_id: Some(result_id),
items: self.diagnostics_of(uri),
};
DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport {
related_documents: None,
full_document_diagnostic_report: full,
})
}
/// Every open buffer's diagnostics, in URI order so two pulls of the same
/// state read the same way.
///
/// Open buffers are the whole scope: this server has never diagnosed a
/// file it was not shown, and pulling would be the wrong place to start —
/// linting the workspace on a keystroke-driven request is a rescan of
/// every file per pull. The limit is stated in the feature README.
pub(super) fn workspace_report(
&self,
previous: &[PreviousResultId],
) -> WorkspaceDiagnosticReport {
let result_id = self.result_id();
let mut uris = self.workspace.open_uris();
uris.sort();
let items = uris
.into_iter()
.map(|uri| {
let known = previous.iter().any(|seen| seen.uri == uri && seen.value == result_id);
if known {
let unchanged =
UnchangedDocumentDiagnosticReport { result_id: result_id.clone() };
return WorkspaceDocumentDiagnosticReport::Unchanged(
WorkspaceUnchangedDocumentDiagnosticReport {
uri,
version: None,
unchanged_document_diagnostic_report: unchanged,
},
);
}
let full = FullDocumentDiagnosticReport {
result_id: Some(result_id.clone()),
items: self.diagnostics_of(&uri),
};
WorkspaceDocumentDiagnosticReport::Full(WorkspaceFullDocumentDiagnosticReport {
uri,
version: None,
full_document_diagnostic_report: full,
})
})
.collect();
WorkspaceDiagnosticReport { items }
}
/// What a report is stamped with: the generation everything was computed
/// against. Coarse on purpose — a change anywhere costs one extra full
/// report elsewhere, and a stale "unchanged" would cost a wrong squiggle.
fn result_id(&self) -> String {
self.generation.to_string()
}
}