use super::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSeverity {
Error,
Warning,
Information,
Hint,
}
#[derive(Debug, Clone)]
pub struct Diagnostic {
pub start_line: u32,
pub start_char: u32,
pub end_line: u32,
pub end_char: u32,
pub severity: DiagnosticSeverity,
pub message: String,
pub tags: DiagnosticTags,
pub code: Option<DiagnosticCode>,
pub origin: Option<std::sync::Arc<DiagnosticOrigin>>,
}
impl PartialEq for Diagnostic {
fn eq(&self, other: &Self) -> bool {
let Diagnostic {
start_line,
start_char,
end_line,
end_char,
severity,
message,
tags,
code,
origin: _,
} = self;
(start_line, start_char, end_line, end_char)
== (
&other.start_line,
&other.start_char,
&other.end_line,
&other.end_char,
)
&& (severity, message, tags, code)
== (&other.severity, &other.message, &other.tags, &other.code)
&& self.related() == other.related()
}
}
#[derive(Debug, PartialEq)]
pub struct DiagnosticOrigin {
pub server: String,
pub wire: lsp_types::Diagnostic,
}
impl Diagnostic {
pub fn related(&self) -> Vec<RelatedLocation> {
let Some(origin) = self.origin.as_deref() else {
return Vec::new();
};
origin
.wire
.related_information
.iter()
.flatten()
.filter_map(|r| {
Some(RelatedLocation {
path: r.location.uri.to_file_path().ok()?,
line: r.location.range.start.line,
character: r.location.range.start.character,
message: r.message.clone(),
})
})
.collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelatedLocation {
pub path: PathBuf,
pub line: u32,
pub character: u32,
pub message: String,
}
impl RelatedLocation {
pub fn label(&self, root: &Path) -> String {
let file = self.path.strip_prefix(root).unwrap_or(&self.path);
format!(
"{}({}, {}): {}",
file.display(),
self.line + 1,
self.character + 1,
one_line(&self.message)
)
}
}
pub fn one_line(text: &str) -> String {
text.replace("\r\n", " ").replace(['\r', '\n'], " ")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticCode {
pub value: String,
pub source: Option<String>,
pub href: Option<String>,
}
impl DiagnosticCode {
pub fn label(&self, fallback_source: &str) -> String {
let source = self.source.as_deref().unwrap_or(fallback_source);
if source.is_empty() {
self.value.clone()
} else {
format!("{source}({})", self.value)
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DiagnosticTags {
pub unnecessary: bool,
pub deprecated: bool,
}
impl DiagnosticTags {
pub fn any(self) -> bool {
self.unnecessary || self.deprecated
}
}
#[derive(Debug, Clone)]
pub struct DiagnosticsUpdate {
pub path: PathBuf,
pub server: String,
pub diagnostics: Vec<Diagnostic>,
pub pulled: bool,
}
pub(super) const PULLED_DIAGNOSTICS: &str = "\u{0}pulled";
pub fn diagnostics_store_key(u: &DiagnosticsUpdate) -> String {
if u.pulled {
format!("{}{PULLED_DIAGNOSTICS}", u.server)
} else {
u.server.clone()
}
}
pub fn diagnostics_source(key: &str) -> &str {
key.strip_suffix(PULLED_DIAGNOSTICS).unwrap_or(key)
}
pub fn diagnostics_by_source(
by_server: &std::collections::HashMap<String, Vec<Diagnostic>>,
) -> impl Iterator<Item = (&str, &Diagnostic)> {
by_server.iter().flat_map(move |(key, diags)| {
let source = diagnostics_source(key);
let pushed = key
.ends_with(PULLED_DIAGNOSTICS)
.then(|| by_server.get(source))
.flatten();
diags
.iter()
.filter(move |d| !pushed.is_some_and(|p| p.contains(d)))
.map(move |d| (source, d))
})
}
impl LspManager {
pub fn drain_diagnostics(&self) -> Option<DiagnosticsUpdate> {
loop {
let u = self.replies.diagnostics.try_recv().ok()?;
let registered = self
.registered_servers
.values()
.any(|names| names.contains(&u.server.as_str()));
if registered || u.diagnostics.is_empty() {
return Some(u);
}
}
}
#[cfg(test)]
pub fn push_diagnostics_for_test(&self, update: DiagnosticsUpdate) {
let _ = self.reply_test_tx.diagnostics.send(update);
}
pub fn take_diagnostic_refresh(&self) -> bool {
self.diagnostic_refresh.swap(false, Ordering::Relaxed)
}
pub fn request_workspace_diagnostics(&self) {
let _ = self.cmd_tx.send(Cmd::RequestWorkspaceDiagnostics);
}
pub fn document_reported_by(&self, path: &Path, name: &str) -> bool {
self.capability_support.lock().is_ok_and(|s| {
s.document_servers
.get(path)
.is_some_and(|names| names.iter().any(|n| n == name))
})
}
}
impl WorkerState {
pub(super) fn request_workspace_diagnostics(&self) {
spawn_workspace_pull(
workspace_pull_targets(self.clients.values().flatten()),
self.diagnostics_tx.clone(),
);
for (path, doc) in &self.docs {
let Ok(uri) = Url::from_file_path(path) else {
continue;
};
let key: ClientKey = (doc.language, doc.project_root.clone());
let pulls = self
.clients
.get(&key)
.map(|cs| document_pull_targets(cs.iter(), path, &uri, &self.capability_support))
.unwrap_or_default();
spawn_document_pulls(
pulls,
self.diagnostics_tx.clone(),
std::time::Duration::ZERO,
);
}
}
}
impl DiagnosticResultIds {
pub fn previous(&self) -> Vec<lsp_types::PreviousResultId> {
self.by_uri
.iter()
.filter_map(|(uri, value)| {
Url::parse(uri).ok().map(|uri| lsp_types::PreviousResultId {
uri,
value: value.clone(),
})
})
.collect()
}
pub fn record(&mut self, uri: &str, result_id: Option<&str>) {
match result_id {
Some(id) => {
self.by_uri.insert(uri.to_string(), id.to_string());
}
None => {
self.by_uri.remove(uri);
}
}
}
pub fn len(&self) -> usize {
self.by_uri.len()
}
#[cfg_attr(not(test), allow(dead_code))]
pub fn is_empty(&self) -> bool {
self.by_uri.is_empty()
}
}
pub(super) const WORKSPACE_PULL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
pub(super) fn workspace_pull_targets<'a>(
clients: impl Iterator<Item = &'a ManagedClient>,
) -> Vec<WorkspacePull> {
clients
.filter(|c| c.supports_workspace_diagnostics)
.filter(|c| !c.diagnostic_pull_stalled.load(Ordering::Relaxed))
.map(|c| WorkspacePull {
name: c.name.clone(),
client: c.client.clone(),
identifier: c.diagnostic_identifier.clone(),
result_ids: c.diagnostic_result_ids.clone(),
stalled: c.diagnostic_pull_stalled.clone(),
})
.collect()
}
pub(super) fn spawn_workspace_pull(
targets: Vec<WorkspacePull>,
tx: std_mpsc::Sender<DiagnosticsUpdate>,
) {
spawn_workspace_pull_within(targets, tx, WORKSPACE_PULL_TIMEOUT);
}
pub(super) fn spawn_workspace_pull_within(
targets: Vec<WorkspacePull>,
tx: std_mpsc::Sender<DiagnosticsUpdate>,
ceiling: std::time::Duration,
) {
if targets.is_empty() {
return;
}
tokio::spawn(async move {
for target in targets {
let mut ids = target.result_ids.lock().await;
if target.stalled.load(Ordering::Relaxed) {
log_file::log(&format!(
"lsp[{}] workspace/diagnostic skipped: retired while queued",
target.name
));
continue;
}
let previous = ids.previous();
let server = {
let client = target.client.lock().await;
client.detached_server()
};
log_file::log(&format!(
"lsp[{}] workspace/diagnostic pull, {} previous result id(s)",
target.name,
previous.len()
));
let resp = match tokio::time::timeout(
ceiling,
crate::lsp::client::LspRequests::workspace_diagnostics_on(
server,
target.identifier.clone(),
previous,
),
)
.await
{
Ok(resp) => resp,
Err(_) => {
target.stalled.store(true, Ordering::Relaxed);
log_file::log(&format!(
"lsp[{}] workspace/diagnostic timed out after {}s; \
retiring it from workspace pulls for this session",
target.name,
ceiling.as_secs()
));
continue;
}
};
match resp {
Ok(result) => {
let forwarded = apply_workspace_report(&target.name, result, &mut ids, &tx);
log_file::log(&format!(
"lsp[{}] workspace/diagnostic: {forwarded} file(s) reported, {} id(s) cached",
target.name,
ids.len()
));
}
Err(e) => {
log_file::log(&format!(
"lsp[{}] workspace/diagnostic error: {e:#}",
target.name
));
}
}
drop(ids);
}
});
}
pub(super) fn apply_workspace_report(
server: &str,
result: lsp_types::WorkspaceDiagnosticReportResult,
ids: &mut DiagnosticResultIds,
tx: &std_mpsc::Sender<DiagnosticsUpdate>,
) -> usize {
let items = match result {
lsp_types::WorkspaceDiagnosticReportResult::Report(r) => r.items,
lsp_types::WorkspaceDiagnosticReportResult::Partial(p) => p.items,
};
let mut forwarded = 0;
for item in items {
match item {
lsp_types::WorkspaceDocumentDiagnosticReport::Unchanged(u) => {
ids.record(
u.uri.as_str(),
Some(u.unchanged_document_diagnostic_report.result_id.as_str()),
);
}
lsp_types::WorkspaceDocumentDiagnosticReport::Full(f) => {
let report = f.full_document_diagnostic_report;
ids.record(f.uri.as_str(), report.result_id.as_deref());
let Ok(path) = f.uri.to_file_path() else {
continue;
};
let diagnostics = report
.items
.iter()
.map(|d| crate::lsp::client::convert_diagnostic(server, d))
.collect();
let _ = tx.send(DiagnosticsUpdate {
path,
server: server.to_string(),
diagnostics,
pulled: true,
});
forwarded += 1;
}
}
}
forwarded
}
pub(super) const DOCUMENT_PULL_DEBOUNCE: std::time::Duration =
std::time::Duration::from_millis(150);
pub(super) const DOCUMENT_PULL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
pub(super) static NEXT_DOCUMENT_PULL: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(1);
pub(super) struct DocumentPull {
name: String,
client: Arc<TokioMutex<LspClient>>,
identifier: Option<String>,
stalled: Arc<AtomicBool>,
generations: Arc<StdMutex<HashMap<PathBuf, u64>>>,
generation: u64,
path: PathBuf,
uri: Url,
reports_per_workspace: bool,
support: CapabilitySupport,
}
impl DocumentPull {
pub(super) fn is_current(&self) -> bool {
let generations = self.generations.lock().unwrap_or_else(|e| e.into_inner());
generations.get(&self.path) == Some(&self.generation)
}
pub(super) fn retire(&self, tx: &std_mpsc::Sender<DiagnosticsUpdate>) {
let served: Vec<PathBuf> = self
.generations
.lock()
.unwrap_or_else(|e| e.into_inner())
.keys()
.cloned()
.collect();
if let Ok(mut support) = self.support.lock() {
for path in &served {
if let Some(names) = support.document_servers.get_mut(path) {
names.retain(|n| *n != self.name);
}
}
}
if self.reports_per_workspace {
return;
}
for path in served {
let _ = tx.send(DiagnosticsUpdate {
path,
server: self.name.clone(),
diagnostics: Vec::new(),
pulled: true,
});
}
}
}
pub(super) fn document_pull_targets<'a>(
clients: impl Iterator<Item = &'a ManagedClient>,
path: &Path,
uri: &Url,
support: &CapabilitySupport,
) -> Vec<DocumentPull> {
clients
.filter(|c| c.supports_document_diagnostics)
.filter(|c| !c.document_pull_stalled.load(Ordering::Relaxed))
.map(|c| {
let generation = {
let mut generations = c
.document_pull_generations
.lock()
.unwrap_or_else(|e| e.into_inner());
let next = NEXT_DOCUMENT_PULL.fetch_add(1, Ordering::Relaxed);
generations.insert(path.to_path_buf(), next);
next
};
DocumentPull {
name: c.name.clone(),
client: c.client.clone(),
identifier: c.diagnostic_identifier.clone(),
stalled: c.document_pull_stalled.clone(),
generations: c.document_pull_generations.clone(),
generation,
path: path.to_path_buf(),
uri: uri.clone(),
reports_per_workspace: c.supports_workspace_diagnostics,
support: support.clone(),
}
})
.collect()
}
pub(super) fn spawn_document_pulls(
targets: Vec<DocumentPull>,
tx: std_mpsc::Sender<DiagnosticsUpdate>,
debounce: std::time::Duration,
) {
spawn_document_pulls_within(targets, tx, debounce, DOCUMENT_PULL_TIMEOUT);
}
pub(super) fn spawn_document_pulls_within(
targets: Vec<DocumentPull>,
tx: std_mpsc::Sender<DiagnosticsUpdate>,
debounce: std::time::Duration,
ceiling: std::time::Duration,
) {
for target in targets {
let tx = tx.clone();
tokio::spawn(async move {
if !debounce.is_zero() {
tokio::time::sleep(debounce).await;
}
if !target.is_current() || target.stalled.load(Ordering::Relaxed) {
return;
}
let server = {
let client = target.client.lock().await;
client.detached_server()
};
let resp = tokio::time::timeout(
ceiling,
crate::lsp::client::LspRequests::document_diagnostics_on(
server,
target.uri.clone(),
target.identifier.clone(),
),
)
.await;
let report = match resp {
Ok(Ok(report)) => report,
Ok(Err(e)) => {
log_file::log(&format!(
"lsp[{}] textDocument/diagnostic error: {e:#}",
target.name
));
return;
}
Err(_) => {
target.stalled.store(true, Ordering::Relaxed);
log_file::log(&format!(
"lsp[{}] textDocument/diagnostic timed out after {}s; \
retiring it from document pulls for this session",
target.name,
ceiling.as_secs()
));
target.retire(&tx);
return;
}
};
if !target.is_current() {
return;
}
let Some(items) = document_report_items(report) else {
return;
};
let _ = tx.send(DiagnosticsUpdate {
path: target.path.clone(),
server: target.name.clone(),
diagnostics: items
.iter()
.map(|d| crate::lsp::client::convert_diagnostic(&target.name, d))
.collect(),
pulled: true,
});
});
}
}
pub(super) fn document_report_items(
result: lsp_types::DocumentDiagnosticReportResult,
) -> Option<Vec<lsp_types::Diagnostic>> {
match result {
lsp_types::DocumentDiagnosticReportResult::Report(
lsp_types::DocumentDiagnosticReport::Full(full),
) => Some(full.full_document_diagnostic_report.items),
_ => None,
}
}
pub(super) fn diagnostic_identifier_of(
cap: &Option<DiagnosticServerCapabilities>,
) -> Option<String> {
match cap {
Some(DiagnosticServerCapabilities::Options(o)) => o.identifier.clone(),
Some(DiagnosticServerCapabilities::RegistrationOptions(r)) => {
r.diagnostic_options.identifier.clone()
}
None => None,
}
}
pub(super) fn workspace_diagnostics_supported(cap: &Option<DiagnosticServerCapabilities>) -> bool {
match cap {
Some(DiagnosticServerCapabilities::Options(o)) => o.workspace_diagnostics,
Some(DiagnosticServerCapabilities::RegistrationOptions(r)) => {
r.diagnostic_options.workspace_diagnostics
}
None => false,
}
}