Skip to content

Commit c5a1bd9

Browse files
committed
feat: Implement diagnostics pull model
1 parent 7147bc9 commit c5a1bd9

File tree

5 files changed

+150
-18
lines changed

5 files changed

+150
-18
lines changed

src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics.rs

+19-15
Original file line numberDiff line numberDiff line change
@@ -173,21 +173,6 @@ pub(crate) fn fetch_native_diagnostics(
173173
let _p = tracing::info_span!("fetch_native_diagnostics").entered();
174174
let _ctx = stdx::panic_context::enter("fetch_native_diagnostics".to_owned());
175175

176-
let convert_diagnostic =
177-
|line_index: &crate::line_index::LineIndex, d: ide::Diagnostic| lsp_types::Diagnostic {
178-
range: lsp::to_proto::range(line_index, d.range.range),
179-
severity: Some(lsp::to_proto::diagnostic_severity(d.severity)),
180-
code: Some(lsp_types::NumberOrString::String(d.code.as_str().to_owned())),
181-
code_description: Some(lsp_types::CodeDescription {
182-
href: lsp_types::Url::parse(&d.code.url()).unwrap(),
183-
}),
184-
source: Some("rust-analyzer".to_owned()),
185-
message: d.message,
186-
related_information: None,
187-
tags: d.unused.then(|| vec![lsp_types::DiagnosticTag::UNNECESSARY]),
188-
data: None,
189-
};
190-
191176
// the diagnostics produced may point to different files not requested by the concrete request,
192177
// put those into here and filter later
193178
let mut odd_ones = Vec::new();
@@ -246,3 +231,22 @@ pub(crate) fn fetch_native_diagnostics(
246231
}
247232
diagnostics
248233
}
234+
235+
pub(crate) fn convert_diagnostic(
236+
line_index: &crate::line_index::LineIndex,
237+
d: ide::Diagnostic,
238+
) -> lsp_types::Diagnostic {
239+
lsp_types::Diagnostic {
240+
range: lsp::to_proto::range(line_index, d.range.range),
241+
severity: Some(lsp::to_proto::diagnostic_severity(d.severity)),
242+
code: Some(lsp_types::NumberOrString::String(d.code.as_str().to_owned())),
243+
code_description: Some(lsp_types::CodeDescription {
244+
href: lsp_types::Url::parse(&d.code.url()).unwrap(),
245+
}),
246+
source: Some("rust-analyzer".to_owned()),
247+
message: d.message,
248+
related_information: None,
249+
tags: d.unused.then(|| vec![lsp_types::DiagnosticTag::UNNECESSARY]),
250+
data: None,
251+
}
252+
}

src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs

+24
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,30 @@ impl RequestDispatcher<'_> {
120120
self.on_with_thread_intent::<true, ALLOW_RETRYING, R>(ThreadIntent::Worker, f)
121121
}
122122

123+
/// Dispatches a non-latency-sensitive request onto the thread pool. When the VFS is marked not
124+
/// ready this will return a default constructed [`R::Result`].
125+
pub(crate) fn on_or<const ALLOW_RETRYING: bool, R>(
126+
&mut self,
127+
f: fn(GlobalStateSnapshot, R::Params) -> anyhow::Result<R::Result>,
128+
default: impl FnOnce() -> R::Result,
129+
) -> &mut Self
130+
where
131+
R: lsp_types::request::Request<
132+
Params: DeserializeOwned + panic::UnwindSafe + Send + fmt::Debug,
133+
Result: Serialize,
134+
> + 'static,
135+
{
136+
if !self.global_state.vfs_done {
137+
if let Some(lsp_server::Request { id, .. }) =
138+
self.req.take_if(|it| it.method == R::METHOD)
139+
{
140+
self.global_state.respond(lsp_server::Response::new_ok(id, default()));
141+
}
142+
return self;
143+
}
144+
self.on_with_thread_intent::<true, ALLOW_RETRYING, R>(ThreadIntent::Worker, f)
145+
}
146+
123147
/// Dispatches a non-latency-sensitive request onto the thread pool. When the VFS is marked not
124148
/// ready this will return the parameter as is.
125149
pub(crate) fn on_identity<const ALLOW_RETRYING: bool, R, Params>(

src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs

+65-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
use std::{
55
fs,
66
io::Write as _,
7+
ops::Not,
78
process::{self, Stdio},
89
};
910

@@ -14,7 +15,7 @@ use ide::{
1415
FilePosition, FileRange, HoverAction, HoverGotoTypeData, InlayFieldsToResolve, Query,
1516
RangeInfo, ReferenceCategory, Runnable, RunnableKind, SingleResolve, SourceChange, TextEdit,
1617
};
17-
use ide_db::SymbolKind;
18+
use ide_db::{FxHashMap, SymbolKind};
1819
use itertools::Itertools;
1920
use lsp_server::ErrorCode;
2021
use lsp_types::{
@@ -36,6 +37,7 @@ use vfs::{AbsPath, AbsPathBuf, FileId, VfsPath};
3637

3738
use crate::{
3839
config::{Config, RustfmtConfig, WorkspaceSymbolConfig},
40+
diagnostics::convert_diagnostic,
3941
global_state::{FetchWorkspaceRequest, GlobalState, GlobalStateSnapshot},
4042
hack_recover_crate_name,
4143
line_index::LineEndings,
@@ -473,6 +475,68 @@ pub(crate) fn handle_on_type_formatting(
473475
Ok(Some(change))
474476
}
475477

478+
pub(crate) fn handle_document_diagnostics(
479+
snap: GlobalStateSnapshot,
480+
params: lsp_types::DocumentDiagnosticParams,
481+
) -> anyhow::Result<lsp_types::DocumentDiagnosticReportResult> {
482+
let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
483+
let source_root = snap.analysis.source_root_id(file_id)?;
484+
let line_index = snap.file_line_index(file_id)?;
485+
let config = snap.config.diagnostics(Some(source_root));
486+
if !config.enabled {
487+
return Ok(lsp_types::DocumentDiagnosticReportResult::Report(
488+
lsp_types::DocumentDiagnosticReport::Full(
489+
lsp_types::RelatedFullDocumentDiagnosticReport {
490+
related_documents: None,
491+
full_document_diagnostic_report: lsp_types::FullDocumentDiagnosticReport {
492+
result_id: None,
493+
items: vec![],
494+
},
495+
},
496+
),
497+
));
498+
}
499+
let supports_related = snap.config.text_document_diagnostic_related_document_support();
500+
501+
let mut related_documents = FxHashMap::default();
502+
let diagnostics = snap
503+
.analysis
504+
.full_diagnostics(&config, AssistResolveStrategy::None, file_id)?
505+
.into_iter()
506+
.filter_map(|d| {
507+
let file = d.range.file_id;
508+
let diagnostic = convert_diagnostic(&line_index, d);
509+
if file == file_id {
510+
return Some(diagnostic);
511+
}
512+
if supports_related {
513+
related_documents.entry(file).or_insert_with(Vec::new).push(diagnostic);
514+
}
515+
None
516+
});
517+
Ok(lsp_types::DocumentDiagnosticReportResult::Report(
518+
lsp_types::DocumentDiagnosticReport::Full(lsp_types::RelatedFullDocumentDiagnosticReport {
519+
full_document_diagnostic_report: lsp_types::FullDocumentDiagnosticReport {
520+
result_id: None,
521+
items: diagnostics.collect(),
522+
},
523+
related_documents: related_documents.is_empty().not().then(|| {
524+
related_documents
525+
.into_iter()
526+
.map(|(id, items)| {
527+
(
528+
to_proto::url(&snap, id),
529+
lsp_types::DocumentDiagnosticReportKind::Full(
530+
lsp_types::FullDocumentDiagnosticReport { result_id: None, items },
531+
),
532+
)
533+
})
534+
.collect()
535+
}),
536+
}),
537+
))
538+
}
539+
476540
pub(crate) fn handle_document_symbol(
477541
snap: GlobalStateSnapshot,
478542
params: lsp_types::DocumentSymbolParams,

src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,15 @@ pub fn server_capabilities(config: &Config) -> ServerCapabilities {
155155
"ssr": true,
156156
"workspaceSymbolScopeKindFiltering": true,
157157
})),
158-
diagnostic_provider: None,
158+
diagnostic_provider: Some(lsp_types::DiagnosticServerCapabilities::Options(
159+
lsp_types::DiagnosticOptions {
160+
identifier: None,
161+
inter_file_dependencies: true,
162+
// FIXME
163+
workspace_diagnostics: false,
164+
work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None },
165+
},
166+
)),
159167
inline_completion_provider: None,
160168
}
161169
}
@@ -380,6 +388,15 @@ impl ClientCapabilities {
380388
.unwrap_or_default()
381389
}
382390

391+
pub fn text_document_diagnostic(&self) -> bool {
392+
(|| -> _ { self.0.text_document.as_ref()?.diagnostic.as_ref() })().is_some()
393+
}
394+
395+
pub fn text_document_diagnostic_related_document_support(&self) -> bool {
396+
(|| -> _ { self.0.text_document.as_ref()?.diagnostic.as_ref()?.related_document_support })()
397+
== Some(true)
398+
}
399+
383400
pub fn code_action_group(&self) -> bool {
384401
self.experimental_bool("codeActionGroup")
385402
}

src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,8 @@ impl GlobalState {
417417
}
418418
}
419419

420+
let supports_diagnostic_pull_model = self.config.text_document_diagnostic();
421+
420422
let client_refresh = became_quiescent || state_changed;
421423
if client_refresh {
422424
// Refresh semantic tokens if the client supports it.
@@ -434,11 +436,21 @@ impl GlobalState {
434436
if self.config.inlay_hints_refresh() {
435437
self.send_request::<lsp_types::request::InlayHintRefreshRequest>((), |_, _| ());
436438
}
439+
440+
if supports_diagnostic_pull_model {
441+
self.send_request::<lsp_types::request::WorkspaceDiagnosticRefresh>(
442+
(),
443+
|_, _| (),
444+
);
445+
}
437446
}
438447

439448
let project_or_mem_docs_changed =
440449
became_quiescent || state_changed || memdocs_added_or_removed;
441-
if project_or_mem_docs_changed && self.config.publish_diagnostics(None) {
450+
if project_or_mem_docs_changed
451+
&& !supports_diagnostic_pull_model
452+
&& self.config.publish_diagnostics(None)
453+
{
442454
self.update_diagnostics();
443455
}
444456
if project_or_mem_docs_changed && self.config.test_explorer() {
@@ -1080,6 +1092,17 @@ impl GlobalState {
10801092
.on_latency_sensitive::<NO_RETRY, lsp_request::SemanticTokensRangeRequest>(handlers::handle_semantic_tokens_range)
10811093
// FIXME: Some of these NO_RETRY could be retries if the file they are interested didn't change.
10821094
// All other request handlers
1095+
.on_or::<NO_RETRY, lsp_request::DocumentDiagnosticRequest>(handlers::handle_document_diagnostics, || lsp_types::DocumentDiagnosticReportResult::Report(
1096+
lsp_types::DocumentDiagnosticReport::Full(
1097+
lsp_types::RelatedFullDocumentDiagnosticReport {
1098+
related_documents: None,
1099+
full_document_diagnostic_report: lsp_types::FullDocumentDiagnosticReport {
1100+
result_id: None,
1101+
items: vec![],
1102+
},
1103+
},
1104+
),
1105+
))
10831106
.on::<RETRY, lsp_request::DocumentSymbolRequest>(handlers::handle_document_symbol)
10841107
.on::<RETRY, lsp_request::FoldingRangeRequest>(handlers::handle_folding_range)
10851108
.on::<NO_RETRY, lsp_request::SignatureHelpRequest>(handlers::handle_signature_help)

0 commit comments

Comments
 (0)